<?php
/***************************************************************************
*                            Dolphin Smart Community Builder
*                              -------------------
*     begin                : Mon Mar 23 2006
*     copyright            : (C) 2007 BoonEx Location
*     website              : http://www.boonex.com
* This file is part of Dolphin - Smart Community Builder
*
* Dolphin is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the
* License, or  any later version.
*
* Dolphin is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with Dolphin,
* see license.txt file; if not, write to marketing@boonex.com
***************************************************************************/

function modzzz_location_import ($sClassPostfix, $aModuleOverwright = array()) {
    global $aModule;
    $a = $aModuleOverwright ? $aModuleOverwright : $aModule;
    if (!$a || $a['uri'] != 'location') {
        $oMain = BxDolModule::getInstance('BxLocationModule');
        $a = $oMain->_aModule;
    }
    bx_import ($sClassPostfix, $a) ;
}

bx_import('BxDolPaginate');
bx_import('BxDolAlerts');
bx_import('BxDolTwigModule');
bx_import('BxTemplSearchResult');
bx_import('BxDolCategories');


define ('BX_LOCATION_PHOTOS_CAT', 'Location');
define ('BX_LOCATION_PHOTOS_TAG', 'location');

define ('BX_LOCATION_VIDEOS_CAT', 'Location');
define ('BX_LOCATION_VIDEOS_TAG', 'location');

define ('BX_LOCATION_SOUNDS_CAT', 'Location');
define ('BX_LOCATION_SOUNDS_TAG', 'location');

define ('BX_LOCATION_FILES_CAT', 'Location');
define ('BX_LOCATION_FILES_TAG', 'location');

define ('BX_LOCATION_MAX_FANS', 1000);

 
/*[begin] map integration*/
require_once( BX_DIRECTORY_PATH_PLUGINS . 'Services_JSON.php' );
 
define ('BX_LOCATION_ZOOM_PROFILES', 10);
define ('BX_LOCATION_ZOOM_CITIES', 5);
define ('BX_LOCATION_ZOOM_COUNTRIES', 1);
define ('BX_LOCATION_DEFAULT_PRIVACY', 3); 
/*[end] map integration*/

 
/*
 * Location module
 *
 * This module allow users to create user's location, 
 * users can rate, comment and discuss location.
 * Location can have photos, videos, sounds and files, uploaded
 * by location's admins.
 *
 * 
 *
 * Profile's Wall:
 * 'add location' event is displayed in profile's wall
 *
 *
 *
 * Spy:
 * The following qactivity is displayed for content_activity:
 * add - new location was created
 * change - location was chaned
 * rate - somebody rated location
 * commentPost - somebody posted comment in location
 *
 *
 *
 * Memberships/ACL:
 * location view location - BX_LOCATION_VIEW_LOCATION
 * location browse - BX_LOCATION_BROWSE
 * location search - BX_LOCATION_SEARCH
 * location add location - BX_LOCATION_ADD_LOCATION
 * location comments delete and edit - BX_LOCATION_COMMENTS_DELETE_AND_EDIT
 * location edit any location - BX_LOCATION_EDIT_ANY_LOCATION
 * location delete any location - BX_LOCATION_DELETE_ANY_LOCATION
 * location mark as featured - BX_LOCATION_MARK_AS_FEATURED
 * location approve location - BX_LOCATION_APPROVE_LOCATION
 *
 * 
 *
 * Service methods:
 *
 * Homepage block with different location
 * @see BxLocationModule::serviceHomepageBlock
 * BxDolService::call('location', 'homepage_block', array());
 *
 * Profile block with user's location
 * @see BxLocationModule::serviceProfileBlock
 * BxDolService::call('location', 'profile_block', array($iProfileId));
 *

 *
 * Member menu item for location (for internal usage only)
 * @see BxLocationModule::serviceGetMemberMenuItem
 * BxDolService::call('location', 'get_member_menu_item', array());
 *
 *
 *
 * Alerts:
 * Alerts type/unit - 'modzzz_location'
 * The following alerts are rised
 *
 
 *
 *  add - new location was added
 *      $iObjectId - location id
 *      $iSenderId - creator of a location
 *      $aExtras['Status'] - status of added location
 *
 *  change - location's info was changed
 *      $iObjectId - location id
 *      $iSenderId - editor user id
 *      $aExtras['Status'] - status of changed location
 *
 *  delete - location was deleted
 *      $iObjectId - location id
 *      $iSenderId - deleter user id
 *
 *  mark_as_featured - location was marked/unmarked as featured
 *      $iObjectId - location id
 *      $iSenderId - performer id
 *      $aExtras['Featured'] - 1 - if location was marked as featured and 0 - if location was removed from featured 
 *
 */
class BxLocationModule extends BxDolTwigModule {

    var $_oPrivacy;
    var $_oMapPrivacy;
    
	var $_aQuickCache = array ();

    function BxLocationModule(&$aModule) {

        parent::BxDolTwigModule($aModule);        
        $this->_sFilterName = 'modzzz_location_filter';
        $this->_sPrefix = 'modzzz_location';

        bx_import ('Privacy', $aModule);
        $this->_oPrivacy = new BxLocationPrivacy($this);

        bx_import ('MapPrivacy', $aModule);
        $this->_oMapPrivacy = new BxLocationMapPrivacy($this);

	    $this->_oConfig->init($this->_oDb);

        $GLOBALS['oBxLocationModule'] = &$this;

		//reloads subcategories on Add form
		if($_GET['ajax']=='cat') { 
			$iParentId = $_GET['parent'];
			echo $this->_oDb->getAjaxCategoryOptions($iParentId);
			exit;
		}  

		if($_GET['ajax']=='state') { 
			$sCountryCode = $_GET['country'];
			echo $this->_oDb->getStateOptions($sCountryCode);
			exit;
		}	


    }

    function actionHome () {
        parent::_actionHome(_t('_modzzz_location_page_title_home'));
    }

    function actionFiles ($sUri) {
        parent::_actionFiles ($sUri, _t('_modzzz_location_page_title_files'));
    }

    function actionSounds ($sUri) {
        parent::_actionSounds ($sUri, _t('_modzzz_location_page_title_sounds'));
    }

    function actionVideos ($sUri) {
        parent::_actionVideos ($sUri, _t('_modzzz_location_page_title_videos'));
    }

    function actionPhotos ($sUri) {
        parent::_actionPhotos ($sUri, _t('_modzzz_location_page_title_photos'));
    }

    function actionComments ($sUri) {
        parent::_actionComments ($sUri, _t('_modzzz_location_page_title_comments'));
    }

    function actionBrowseFans ($sUri) {
        parent::_actionBrowseFans ($sUri, 'isAllowedViewFans', 'getFansBrowse', $this->_oDb->getParam('modzzz_location_perpage_browse_fans'), 'browse_fans/', _t('_modzzz_location_page_title_fans'));
    }

    function actionBrowseReviews ($sUri) {
        $this->_actionBrowseReviews ($sUri, _t('_modzzz_location_page_title_reviews'));
    }

    function _actionBrowseReviews ($sUri, $sTitle) {

		$iPerPage=$this->_oDb->getParam('modzzz_location_perpage_browse_reviews');

        if (!($aDataEntry = $this->_preProductTabs($sUri, $sTitle))) { 
            return;
        }
 
        if (!$this->isAllowedViewReviews($aDataEntry)) {            
            $this->_oTemplate->displayAccessDenied ();
            return;
        }        

        $iPage = (int)$_GET['page'];
        if( $iPage < 1)
            $iPage = 1;
        $iStart = ($iPage - 1) * $iPerPage;

        $aProfiles = array ();
        $iNum = $this->_oDb->getReviewsBrowse($aProfiles, $aDataEntry[$this->_oDb->_sFieldId], $iStart, $iPerPage);
        if (!$iNum || !$aProfiles) {
            $this->_oTemplate->displayNoData ();
            return;
        }
        $iPages = ceil($iNum / $iPerPage);
 
        $sRet = '';
        foreach ($aProfiles as $aProfile) {
            $sRet .= $this->_oTemplate->review_unit($aProfile);
        }
        $sRet .= '<div class="clear_both"></div>';        

        bx_import('BxDolPaginate');
        $sUrlStart = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'browse_reviews/' . $aDataEntry[$this->_oDb->_sFieldUri];
        $sUrlStart .= (false === strpos($sUrlStart, '?') ? '?' : '&');

        $oPaginate = new BxDolPaginate(array(
            'page_url' => $sUrlStart . 'page={page}&per_page={per_page}' . (false !== bx_get($this->sFilterName) ? '&' . $this->sFilterName . '=' . bx_get($this->sFilterName) : ''),
            'count' => $iNum,
            'per_page' => $iPerPage,
            'page' => $iPage,
            'per_page_changer' => false,
            'page_reloader' => true,
            'on_change_page' => '',
            'on_change_per_page' => "document.location='" . $sUrlStart . "page=1&per_page=' + this.value + '" . (false !== bx_get($this->sFilterName) ? '&' . $this->sFilterName . '=' . bx_get($this->sFilterName) ."';": "';"),
        ));

        $sRet .= $oPaginate->getPaginate();

        $this->_oTemplate->pageStart();

        $this->_oTemplate->addCss('view.css');
 
        echo DesignBoxContent ($sTitle, $sRet, 1);

        $this->_oTemplate->pageCode($sTitle, false, false);
    }
 
    function actionView ($sUri) {
        parent::_actionView ($sUri, _t('_modzzz_location_msg_pending_approval'));
    }

    function actionUploadPhotos ($sUri) {        
        parent::_actionUploadMedia ($sUri, 'isAllowedUploadPhotos', 'images', array ('images_choice', 'images_upload'), _t('_modzzz_location_page_title_upload_photos'));
    }

    function actionUploadVideos ($sUri) {
        parent::_actionUploadMedia ($sUri, 'isAllowedUploadVideos', 'videos', array ('videos_choice', 'videos_upload'), _t('_modzzz_location_page_title_upload_videos'));
    }

    function actionUploadSounds ($sUri) {
        parent::_actionUploadMedia ($sUri, 'isAllowedUploadSounds', 'sounds', array ('sounds_choice', 'sounds_upload'), _t('_modzzz_location_page_title_upload_sounds')); 
    }

    function actionUploadFiles ($sUri) {
        parent::_actionUploadMedia ($sUri, 'isAllowedUploadFiles', 'files', array ('files_choice', 'files_upload'), _t('_modzzz_location_page_title_upload_files')); 
    }
  
    function actionCalendar ($iYear = '', $iMonth = '') {
        parent::_actionCalendar ($iYear, $iMonth, _t('_modzzz_location_page_title_calendar'));
    }

    function actionSearch ($sKeyword = '', $sCategory = '', $sCountry = '', $sState = '', $sCity = '') {

        if (!$this->isAllowedSearch()) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }

        $this->_oTemplate->pageStart();

        if ($sKeyword) 
            $_GET['Keyword'] = $sKeyword;
        if ($sCategory)
            $_GET['Category'] = $sCategory;
		if ($sCity) 
            $_GET['City'] = $sCity;
		if ($sState) 
            $_GET['State'] = $sState; 
         if ($sCountry)
            $_GET['Country'] = explode(',', $sCountry);


        if (is_array($_GET['Country']) && 1 == count($_GET['Country']) && !$_GET['Country'][0]) {
            unset($_GET['Country']);
            unset($sCountry);
        }
  
        if ($sCountry || $sCategory || $sKeyword || $sState || $sCity ) {
            $_GET['submit_form'] = 1;  
        }
        
        modzzz_location_import ('FormSearch');
        $oForm = new BxLocationFormSearch ();
        $oForm->initChecker();

        if ($oForm->isSubmittedAndValid ()) {
 
            modzzz_location_import ('SearchResult');
            $o = new BxLocationSearchResult('search', $oForm->getCleanValue('Keyword'), $oForm->getCleanValue('Category'), $oForm->getCleanValue('City'), $oForm->getCleanValue('State'), $oForm->getCleanValue('Country') );

            if ($o->isError) {
                $this->_oTemplate->displayPageNotFound ();
                return;
            }

            if ($s = $o->processing()) {
                echo $s;
            } else {
                $this->_oTemplate->displayNoData ();
                return;
            }

            $this->isAllowedSearch(true); // perform search action 

            $this->_oTemplate->addCss ('unit.css');
            $this->_oTemplate->addCss ('main.css');
            $this->_oTemplate->pageCode($o->aCurrent['title'], false, false);
            return;

        } 

        echo $oForm->getCode ();
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->pageCode(_t('_modzzz_location_form_caption_search'));
    } 


    function actionSearchOLD ($sKeyword = '', $sCategory = '', $sCity = '', $sCountry = '') {
 
        if (!$this->isAllowedSearch()) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }

        $this->_oTemplate->pageStart();

        if ($sKeyword) 
            $_REQUEST['Keyword'] = $sKeyword;
        if ($sKeyword) 
            $_REQUEST['City'] = $sCity;
        if ($sCategory)
            $_REQUEST['Category'] = explode(',', $sCategory); 
        if ($sCountry)
            $_REQUEST['Country'] = explode(',', $sCountry);

        if (is_array($_REQUEST['Country']) && 1 == count($_REQUEST['Country']) && !$_REQUEST['Country'][0]) {
            unset ($_REQUEST['Country']);
            unset($sCountry);
        }

        if (is_array($_REQUEST['Category']) && 1 == count($_REQUEST['Category']) && !$_REQUEST['Category'][0]) {
            unset ($_REQUEST['Category']);
            unset($sCategory);
        }
 
        if ($sCategory || $sKeyword || $sCity || $sCountry) {
            $_REQUEST['submit_form'] = 1;
        }
        
        bx_import ('FormSearch', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'FormSearch';
        $oForm = new $sClass ();
        $oForm->initChecker();        

        if ($oForm->isSubmittedAndValid ()) {
 
            bx_import ('SearchResult', $this->_aModule);
            $sClass = $this->_aModule['class_prefix'] . 'SearchResult';
            $o = new $sClass('search', $oForm->getCleanValue('Keyword'), $oForm->getCleanValue('Category'), $oForm->getCleanValue('City'), $oForm->getCleanValue('Country'));
 
            if ($o->isError) {
                $this->_oTemplate->displayPageNotFound ();
                return;
            }

            if ($s = $o->processing()) {
                
                echo $s;
                
            } else {
                $this->_oTemplate->displayNoData ();
                return;
            }

            $this->isAllowedSearch(true); // perform search action 

            $this->_oTemplate->addCss ('unit.css');
            $this->_oTemplate->addCss ('main.css');
            $this->_oTemplate->pageCode($o->aCurrent['title'], false, false); 
			return;
		} 

        echo $oForm->getCode ();
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->pageCode(_t('_modzzz_location_page_title_search'));
    }
  
    function actionAdd () {
        parent::_actionAdd (_t('_modzzz_location_page_title_add'));
    }
  
    function _addForm ($sRedirectUrl) { 
  
        bx_import ('FormAdd', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'FormAdd';
        $oForm = new $sClass ($this, $this->_iProfileId);
        $oForm->initChecker();

        if ($oForm->isSubmittedAndValid ()) {
 
			$sStatus =  ((getParam($this->_sPrefix.'_autoapproval') == 'on') || $this->isAdmin()) ? 'approved' : 'pending';

            $aValsAdd = array (
                $this->_oDb->_sFieldCreated => time(),
                $this->_oDb->_sFieldUri => $oForm->generateUri(),
                $this->_oDb->_sFieldStatus => $sStatus,
            );                        
            $aValsAdd[$this->_oDb->_sFieldAuthorId] = $this->_iProfileId;

            $iEntryId = $oForm->insert ($aValsAdd);
 
            if ($iEntryId) {

                $this->isAllowedAdd(true); // perform action                 
 
				$oForm->processMedia($iEntryId, $this->_iProfileId); 
		  
                $aDataEntry = $this->_oDb->getEntryByIdAndOwner($iEntryId, $this->_iProfileId, $this->isAdmin());
                $this->onEventCreate($iEntryId, $sStatus, $aDataEntry);
  
				if (!$sRedirectUrl)  
					$sRedirectUrl = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri];
			  
                header ('Location:' . $sRedirectUrl);
                exit;

            } else {

                MsgBox(_t('_Error Occured'));
            }
                         
        } else { 

            echo $oForm->getCode (); 
        }
    }

    function actionEdit ($iEntryId) {
        parent::_actionEdit ($iEntryId, _t('_modzzz_location_page_title_edit'));
    }

    function actionDelete ($iEntryId) {
        parent::_actionDelete ($iEntryId, _t('_modzzz_location_msg_location_was_deleted'));
    }

    function actionMarkFeatured ($iEntryId) {
        parent::_actionMarkFeatured ($iEntryId, _t('_modzzz_location_msg_added_to_featured'), _t('_modzzz_location_msg_removed_from_featured'));
    }
 
    function actionSharePopup ($iEntryId) {
        parent::_actionSharePopup ($iEntryId, _t('_modzzz_location_form_caption_share_location'));
    }
 
   function actionJoin ($iEntryId, $iProfileId) {

        parent::_actionJoin ($iEntryId, $iProfileId, _t('_modzzz_location_msg_joined_already'), _t('_modzzz_location_msg_joined_request_pending'), _t('_modzzz_location_msg_join_success'), _t('_modzzz_location_msg_join_success_pending'), _t('_modzzz_location_msg_leave_success'));
    }    
 
    function actionManageFansPopup ($iEntryId) {
        parent::_actionManageFansPopup ($iEntryId, _t('_modzzz_location_form_caption_manage_fans'), 'getFans', 'isAllowedManageFans', 'isAllowedManageAdmins', BX_LOCATION_MAX_FANS);
    }

    function actionTags() {
        parent::_actionTags (_t('_modzzz_location_page_title_tags'));
    }    
 
    function actionPackages () { 
        $this->_oTemplate->pageStart();
        bx_import ('PagePackages', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'PagePackages';
        $oPage = new $sClass ($this,$sUri);
        echo $oPage->getCode();
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('unit.css');
        $this->_oTemplate->pageCode(_t('_modzzz_location_page_title_packages'), false, false);
    }

    function actionCategories ($sUri='') { 
        $this->_oTemplate->pageStart();
        bx_import ('PageCategory', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'PageCategory';
        $oPage = new $sClass ($this,$sUri);
        echo $oPage->getCode();
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('unit.css');
         $this->_oTemplate->pageCode(_t('_modzzz_location_page_title_categories'), false, false);
    }

    function actionSubCategories ($sUri='') {
        $this->_oTemplate->pageStart();
        bx_import ('PageSubCategory', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'PageSubCategory';
        $oPage = new $sClass ($this,$sUri);
        echo $oPage->getCode();
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('unit.css');
         $this->_oTemplate->pageCode(_t('_modzzz_location_page_title_subcategories'), false, false);
    }
 
    function actionDownload ($iEntryId, $iMediaId) {

        $aFileInfo = $this->_oDb->getMedia ((int)$iEntryId, (int)$iMediaId, 'files');

        if (!$aFileInfo || !($aDataEntry = $this->_oDb->getEntryByIdAndOwner((int)$iEntryId, 0, true))) {
            $this->_oTemplate->displayPageNotFound ();
            exit;
        }

        if (!$this->isAllowedView ($aDataEntry)) {
            $this->_oTemplate->displayAccessDenied ();
            exit;
        }

        parent::_actionDownload($aFileInfo, 'media_id');
    }
 
    function actionInvite ($iEntryId) {
        $this->_actionInvite ($iEntryId, 'modzzz_location_invitation', $this->_oDb->getParam('modzzz_location_max_email_invitations'), _t('_modzzz_location_invitation_sent'), _t('_modzzz_location_no_users_msg'), _t('_modzzz_location_form_caption_invite'));
    }

    function _actionInvite ($iEntryId, $sEmailTemplate, $iMaxEmailInvitations, $sMsgInvitationSent, $sMsgNoUsers, $sTitle) {

        $iEntryId = (int)$iEntryId;
        if (!($aDataEntry = $this->_oDb->getEntryById($iEntryId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }

        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);

        bx_import('BxDolTwigFormInviter');
        $oForm = new BxDolTwigFormInviter ($this, $sMsgNoUsers);
        $oForm->initChecker();

        if ($oForm->isSubmittedAndValid ()) {        

            $aInviter = getProfileInfo($this->_iProfileId);
            $aPlusOriginal = $this->_getInviteParams ($aDataEntry, $aInviter);
            
            $oEmailTemplate = new BxDolEmailTemplates();
            $aTemplate = $oEmailTemplate->getTemplate($sEmailTemplate);
            $iSuccess = 0;

            // send invitation to registered members
            if (isset($_REQUEST['inviter_users']) && is_array($_REQUEST['inviter_users'])) {
                foreach ($_REQUEST['inviter_users'] as $iRecipient) {
                    $aRecipient = getProfileInfo($iRecipient);
                    $aPlus = array_merge (array ('NickName' => ' ' . $aRecipient['NickName']), $aPlusOriginal);
                    $iSuccess += sendMail(trim($aRecipient['Email']), $aTemplate['Subject'], $aTemplate['Body'], '', $aPlus) ? 1 : 0;
                }
            }

            // send invitation to additional emails
            $iMaxCount = $iMaxEmailInvitations;
            $aEmails = preg_split ("#[,\s\\b]+#", $_REQUEST['inviter_emails']);
            $aPlus = array_merge (array ('NickName' => ''), $aPlusOriginal);
            if ($aEmails && is_array($aEmails)) {
                foreach ($aEmails as $sEmail) {
                    if (strlen($sEmail) < 5) 
                        continue;
                    $iRet = sendMail(trim($sEmail), $aTemplate['Subject'], $aTemplate['Body'], '', $aPlus) ? 1 : 0;
                    $iSuccess += $iRet;
                    if ($iRet && 0 == --$iMaxCount) 
                        break;
                }             
            }

            $sMsg = sprintf($sMsgInvitationSent, $iSuccess);
            echo MsgBox($sMsg);
            $this->_oTemplate->addCss ('main.css');
            $this->_oTemplate->pageCode ($sMsg, true, false);
            return;
        } 

        echo $oForm->getCode ();
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('inviter.css');
        $this->_oTemplate->pageCode($sTitle . $aDataEntry[$this->_oDb->_sFieldTitle]);
    }
  
    function _getInviteParams ($aDataEntry, $aInviter) {
        return array (
                'LocationName' => $aDataEntry['title'],
                'LocationLocation' => _t($GLOBALS['aPreValues']['country'][$aDataEntry['Country']]['LKey']) . (trim($aDataEntry['city']) ? ', '.$aDataEntry['city'] : ''),
                'LocationUrl' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry['uri'],
                'InviterUrl' => $aInviter ? getProfileLink($aInviter['ID']) : 'javascript:void(0);',
                'InviterNickName' => $aInviter ? $aInviter['NickName'] : _t('_modzzz_location_user_unknown'),
                'InvitationText' => stripslashes(strip_tags($_REQUEST['inviter_text'])),
            );        
    }

 
    function actionInquire ($iEntryId) {
        $this->_actionInquire ($iEntryId, 'modzzz_location_inquiry', _t('_modzzz_location_form_caption_make_inquiry'), _t('_modzzz_location_inquiry_sent'), _t('_modzzz_location_inquiry_not_sent'));
    }

    function _actionInquire ($iEntryId, $sEmailTemplate, $sTitle, $sMsgSuccess, $sMsgFail) {

        $iEntryId = (int)$iEntryId;
        if (!($aDataEntry = $this->_oDb->getEntryById($iEntryId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }

        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);

        bx_import ('InquireForm', $this->_aModule);
		$oForm = new BxLocationInquireForm ($this);
        $oForm->initChecker();

        if ($oForm->isSubmittedAndValid ()) {        
 
			$aInquirer = getProfileInfo($this->_iProfileId);
            $aPlusOriginal = $this->_getInquireParams ($aDataEntry, $aInquirer);
		  
			$iRecipient = $aDataEntry['author_id'];
 
            $oEmailTemplate = new BxDolEmailTemplates();
            $aTemplate = $oEmailTemplate->getTemplate($sEmailTemplate);
            $iSuccess = 0;
  
            // send message to location owner
            if (isset($_REQUEST['inquire_text'])) { 
				 $aRecipient = getProfileInfo($iRecipient); 

				 $sContactEmail = trim($aDataEntry['selleremail']) ? trim($aDataEntry['selleremail']) : trim($aRecipient['Email']);
 
				 $sSubject = str_replace("<NickName>",$aInquirer['NickName'], $aTemplate['Subject']);
				 $sSubject = str_replace("<SiteName>", $GLOBALS['site']['title'], $sSubject);

				 $aPlus = array_merge (array ('RecipientName' => ' ' . $aRecipient['NickName']), $aPlusOriginal);

                 $iSuccess = sendMail($sContactEmail, $sSubject, $aTemplate['Body'], '', $aPlus) ? 1 : 0;  
			}
			
            $sMsg = ($iSuccess) ? $sMsgSuccess : $sMsgFail;
            echo MsgBox($sMsg);
            $this->_oTemplate->addCss ('main.css');
            $this->_oTemplate->pageCode ($sMsg, true, false);
            return;
        } 

        echo $oForm->getCode ();
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('inviter.css');
        $this->_oTemplate->addJsAdmin ('http://www.google.com/jsapi?key=' . getParam('modzzz_location_key'));
        $this->_oTemplate->addJsAdmin (BX_DOL_URL_MODULES . $this->_aModule['path'] . 'js/BxMap.js');
        $this->_oTemplate->pageCode($sTitle . $aDataEntry[$this->_oDb->_sFieldTitle]);
    }

    function _getInquireParams ($aDataEntry, $aInquirer) {
        return array (
                'ListTitle' => $aDataEntry['title'], 
                'ListUrl' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry['uri'],
                'SenderLink' => $aInquirer ? getProfileLink($aInquirer['ID']) : 'javascript:void(0);',
                'SenderName' => $aInquirer ? $aInquirer['NickName'] : _t('_modzzz_location_user_unknown'),
                'Message' => stripslashes(strip_tags($_REQUEST['inquire_text'])),
            );        
    }
  
	//[begin] review
    function actionReview ($iEntryId) {
 
		$this->_actionReview ($iEntryId, _t('_modzzz_location_form_caption_post_review'), _t('_modzzz_location_review_saved'), _t('_modzzz_location_review_not_saved'));
 
	}

    function actionSubReview ($sType, $iEntryId) {
 
		$this->_actionSubReview ($sType, $iEntryId, _t('_modzzz_location_form_caption_post_review'), _t('_modzzz_location_review_saved'), _t('_modzzz_location_review_not_saved'));
 	}

    function _actionReview ($iEntryId, $sTitle, $sMsgSuccess, $sMsgFail) {

        $iEntryId = (int)$iEntryId;
        if (!($aDataEntry = $this->_oDb->getEntryById($iEntryId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }

		$sTitle = $sTitle . $aDataEntry[$this->_oDb->_sFieldTitle];

        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);

		if(!(($GLOBALS['site']['ver']=='7.0') && ($GLOBALS['site']['build']=='0'))) {  	 
			$GLOBALS['oTopMenu']->setCustomBreadcrumbs(array(
				_t('_'.$this->_sPrefix) => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'home/',
				$aDataEntry[$this->_oDb->_sFieldTitle] => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri],
				$sTitle => '',
			));
		}
 
        bx_import ('ReviewForm', $this->_aModule);
		$oForm = new BxLocationReviewForm ($this);
        $oForm->initChecker();

        if ($oForm->isSubmittedAndValid ()) {        
  
            // save review text 
			$iSuccess = $this->_oDb->postReview($iEntryId, $iEntryId, $this->_iProfileId, 'location'); 
  
            $sMsg = ($iSuccess) ? $sMsgSuccess : $sMsgFail;
            echo MsgBox($sMsg);
            $this->_oTemplate->addCss ('main.css');
            $this->_oTemplate->pageCode ($sMsg, true, false);
            return;
        } 

        echo $oForm->getCode ();
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->pageCode($sTitle);
    } 

    function _actionSubReview ($sType, $iSubEntryId, $sTitle, $sMsgSuccess, $sMsgFail) {
 
		$aSubEntry = $this->_oDb->getSubProfileEntryById($sType, $iSubEntryId);
		$iEntryId = (int)$aSubEntry['location_id'];
 
        if (!($aDataEntry = $this->_oDb->getEntryById($iEntryId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }

		$sTitle = $sTitle . $aSubEntry[$this->_oDb->_sFieldTitle] .' - '. $aDataEntry[$this->_oDb->_sFieldTitle];

        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aSubEntry[$this->_oDb->_sFieldTitle] .' - '. $aDataEntry[$this->_oDb->_sFieldTitle]); 
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);

		if(!(($GLOBALS['site']['ver']=='7.0') && ($GLOBALS['site']['build']=='0'))) {  	 
			$GLOBALS['oTopMenu']->setCustomBreadcrumbs(array(
				_t('_'.$this->_sPrefix) => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'home/',
				$aDataEntry[$this->_oDb->_sFieldTitle] => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri],
				$aSubEntry[$this->_oDb->_sFieldTitle] => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . $sType. '/view/' . $aSubEntry[$this->_oDb->_sFieldUri],

				$sTitle => '',
			));
		}

        bx_import ('ReviewForm', $this->_aModule);
		$oForm = new BxLocationReviewForm ($this, $sType);
        $oForm->initChecker();

        if ($oForm->isSubmittedAndValid ()) {        
  
            // save review text 
			$iSuccess = $this->_oDb->postReview($iEntryId, $iSubEntryId, $this->_iProfileId, $sType); 
  
            $sMsg = ($iSuccess) ? $sMsgSuccess : $sMsgFail;
            echo MsgBox($sMsg);
            $this->_oTemplate->addCss ('main.css');
            $this->_oTemplate->pageCode ($sMsg, true, false);
            return;
        } 

        echo $oForm->getCode ();
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->pageCode($sTitle);
    } 
	//[end] review
 
	//[begin] here now
    function actionHere ($iEntryId) { 
		$this->_actionHere ($iEntryId, _t('_modzzz_location_msg_here_now') );
    }
 
    function _actionHere ($iEntryId, $sMsgSuccessAdd ) {

        $iEntryId = (int)$iEntryId;
        if (!($aDataEntry = $this->_oDb->getEntryById($iEntryId))) {
            echo MsgBox(_t('_sys_request_page_not_found_cpt')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }
   
        if ($this->_oDb->addFan($iEntryId, $this->_iProfileId, "here")) {
            $this->isAllowedHere($aDataEntry); // perform action
            $this->onEventHere ($iEntryId, $aDataEntry);
            $sRedirect = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri];
            $sJQueryJS = genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div', $sRedirect);
            echo MsgBox($sMsgSuccessAdd) . $sJQueryJS;
            exit;
        }        

        echo MsgBox(_t('_Error Occured')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
        exit;        
    } 
	//[end] here now


	//[begin] been here now
    function actionBeenHere ($iEntryId) { 
		$this->_actionBeenHere ($iEntryId, _t('_modzzz_location_msg_been_here') );
    }
 
    function _actionBeenHere ($iEntryId, $sMsgSuccessAdd ) {

        $iEntryId = (int)$iEntryId;
        if (!($aDataEntry = $this->_oDb->getEntryById($iEntryId))) {
            echo MsgBox(_t('_sys_request_page_not_found_cpt')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }
   
        if ($this->_oDb->addFan($iEntryId, $this->_iProfileId, "beenhere")) {
            $this->isAllowedBeenHere($aDataEntry); // perform action
            $this->onEventBeenHere ($iEntryId, $aDataEntry);
            $sRedirect = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri];
            $sJQueryJS = genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div', $sRedirect);
            echo MsgBox($sMsgSuccessAdd) . $sJQueryJS;
            exit;
        }        

        echo MsgBox(_t('_Error Occured')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
        exit;        
    } 
	//[end] been here now


	//[begin] going here now
    function actionGoingHere ($iEntryId) { 
		$this->_actionGoingHere ($iEntryId, _t('_modzzz_location_msg_going_here') );
    }
 
    function _actionGoingHere ($iEntryId, $sMsgSuccessAdd ) {

        $iEntryId = (int)$iEntryId;
        if (!($aDataEntry = $this->_oDb->getEntryById($iEntryId))) {
            echo MsgBox(_t('_sys_request_page_not_found_cpt')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }
   
        if ($this->_oDb->addFan($iEntryId, $this->_iProfileId, "goinghere")) {
            $this->isAllowedGoingHere($aDataEntry); // perform action
            $this->onEventGoingHere ($iEntryId, $aDataEntry);
            $sRedirect = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri];
            $sJQueryJS = genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div', $sRedirect);
            echo MsgBox($sMsgSuccessAdd) . $sJQueryJS;
            exit;
        }        

        echo MsgBox(_t('_Error Occured')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
        exit;        
    } 
	//[end] going here now


    function onEventHere ($iEntryId, $aDataEntry) {
		//
    }
 
    function onEventBeenHere ($iEntryId, $aDataEntry) {
		//
    }

    function onEventGoingHere ($iEntryId, $aDataEntry) {
		//
    }

    function isAllowedReview (&$aDataEntry) {
        if (!$this->_iProfileId) 
            return false;        
        if ($this->isAdmin())
            return true;
        if (!$this->_oDb->isFan($aDataEntry['id'], $this->_iProfileId))
            return false;        
        
		return true;  
	}
 
    function isAllowedHere (&$aDataEntry) {
        if (!$this->_iProfileId) 
            return false;  		
		
		return true;
    }

    function isAllowedBeenHere (&$aDataEntry) {
        if (!$this->_iProfileId) 
            return false;        
        
		return true;  
    }

    function isAllowedGoingHere (&$aDataEntry) {
        if (!$this->_iProfileId) 
            return false;  		
		
		return true;
    }


    // ================================== external actions

    /**
     * Homepage block with different location
     * @return html to display on homepage in a block
     */     
    function serviceHomepageBlock () {

        if (!$this->_oDb->isAnyPublicContent()){ 
			return '';
        } 
        bx_import ('PageMain', $this->_aModule);
        $o = new BxLocationPageMain ($this);
        $o->sUrlStart = BX_DOL_URL_ROOT . '?';

        $this->_oTemplate->addCss('unit.css');
  
        $sDefaultHomepageTab = $this->_oDb->getParam('modzzz_location_homepage_default_tab');
        $sBrowseMode = $sDefaultHomepageTab;
        switch ($_GET['modzzz_location_filter']) {            
            case 'featured':
            case 'recent':
            case 'top':
            case 'popular':
            case $sDefaultHomepageTab:            
                $sBrowseMode = $_GET['modzzz_location_filter'];
                break;
        }

        return $o->ajaxBrowse(
            $sBrowseMode,
            $this->_oDb->getParam('modzzz_location_perpage_homepage'), 
            array(
                _t('_modzzz_location_tab_featured') => array('href' => BX_DOL_URL_ROOT . '?modzzz_location_filter=featured', 'active' => 'featured' == $sBrowseMode, 'dynamic' => true),
                _t('_modzzz_location_tab_recent') => array('href' => BX_DOL_URL_ROOT . '?modzzz_location_filter=recent', 'active' => 'recent' == $sBrowseMode, 'dynamic' => true),
                _t('_modzzz_location_tab_top') => array('href' => BX_DOL_URL_ROOT . '?modzzz_location_filter=top', 'active' => 'top' == $sBrowseMode, 'dynamic' => true),
                _t('_modzzz_location_tab_popular') => array('href' => BX_DOL_URL_ROOT . '?modzzz_location_filter=popular', 'active' => 'popular' == $sBrowseMode, 'dynamic' => true),
            )
        );
    }

    /**
     * Profile block with user's location
     * @param $iProfileId profile id 
     * @return html to display on profile in a block
     */     
    function serviceProfileBlock ($iProfileId) {
        $iProfileId = (int)$iProfileId;
        $aProfile = getProfileInfo($iProfileId);
        bx_import ('PageMain', $this->_aModule);
        $o = new BxLocationPageMain ($this);        
        $o->sUrlStart = getProfileLink($aProfile['ID']) . '?';
        
		$this->_oTemplate->addCss('unit.css');

        return $o->ajaxBrowse(
            'user', 
            $this->_oDb->getParam('modzzz_location_perpage_profile'), 
            array(),
            $aProfile['NickName'],
            true,
            false 
        );
    }


    /**
     * Profile block with user's location
     * @param $iProfileId profile id 
     * @return html to display on profile in a block
     */     
    function serviceProfileBeenBlock ($iProfileId) {
        $iProfileId = (int)$iProfileId;
        $aProfile = getProfileInfo($iProfileId);
        bx_import ('PageMain', $this->_aModule);
        $o = new BxLocationPageMain ($this);        
        $o->sUrlStart = getProfileLink($aProfile['ID']) . '?';
        
		$this->_oTemplate->addCss('unit.css');

        return $o->ajaxBrowse(
            'been', 
            $this->_oDb->getParam('modzzz_location_perpage_profile'), 
            array(),
            $aProfile['NickName'],
            true,
            false 
        );
    }
  
    /**
     * Profile block with user's location
     * @param $iProfileId profile id 
     * @return html to display on profile in a block
     */     
    function serviceProfileReviewsBlock ($iProfileId) {
        $iProfileId = (int)$iProfileId;
		
		$aMenu = array();
		
		$this->_oTemplate->addCss('view.css');

		$iPerPage = (int)$this->_oDb->getParam('modzzz_location_perpage_reviews_profile');
       
        $iPage = (int)$_GET['page'];
        if( $iPage < 1)
            $iPage = 1;
        $iStart = ($iPage - 1) * $iPerPage;
  
        $aProfiles = array ();
        $iNum = $this->_oDb->getProfileReviews($aProfiles, $iProfileId, $iStart, $iPerPage);
        if (!$iNum || !$aProfiles) { 
            return;
        }
        $iPages = ceil($iNum / $iPerPage);
 
        $sMainContent = '';
        foreach ($aProfiles as $aProfile) {
            $sMainContent .= $this->_oTemplate->review_unit($aProfile); 
        }
        $sRet  = $GLOBALS['oFunctions']->centerContent($sMainContent, '.searchrow_block_simple');
        $sRet .= '<div class="clear_both"></div>'; 
  

        bx_import('BxDolPaginate');
 
        $sUrlStart = getProfileLink($iProfileId); 
        $sUrlStart .= (false === strpos($sUrlStart, '?') ? '?' : '&');
 
        $oPaginate = new BxDolPaginate(array(
            'page_url' => 'javascript:void(0);',
            'count' => $iNum,
            'per_page' => $iPerPage,
            'page' => $iPage,
            'on_change_page' => 'return !loadDynamicBlock({id}, \'' . $sUrlStart . 'page={page}&per_page={per_page}\');',
        ));
 	    $sAjaxPaginate = $oPaginate->getSimplePaginate('', -1, -1, false);

        return array(
            $sRet, 
            $aMenu,
            $sAjaxPaginate,
            '');  
     }


    /**
     * Profile block with members at user's location
     * @param $iProfileId profile id 
     * @return html to display on profile in a block
     */     
    function serviceProfileCityBlock ($iProfileId) {
        $iProfileId = (int)$iProfileId;
		
		$aMenu = array();
		
		$iPerPage = $this->_oDb->getParam('modzzz_location_perpage_members_profile');
       
        $iPage = (int)$_GET['page'];
        if( $iPage < 1)
            $iPage = 1;
        $iStart = ($iPage - 1) * $iPerPage;

        $aProfiles = array ();
        $iNum = $this->_oDb->getLocalMembers($aProfiles, $iProfileId, $iStart, $iPerPage);
        if (!$iNum || !$aProfiles) { 
            return;
        }
        $iPages = ceil($iNum / $iPerPage);
 
        bx_import('BxTemplSearchProfile');
        $oBxTemplSearchProfile = new BxTemplSearchProfile();
        $sMainContent = '';
        foreach ($aProfiles as $aProfile) {
            $sMainContent .= $oBxTemplSearchProfile->displaySearchUnit($aProfile);
        }
        $sRet  = $GLOBALS['oFunctions']->centerContent($sMainContent, '.searchrow_block_simple');
        $sRet .= '<div class="clear_both"></div>'; 
  

        bx_import('BxDolPaginate');
 
        $sUrlStart = getProfileLink($iProfileId); 
        $sUrlStart .= (false === strpos($sUrlStart, '?') ? '?' : '&');
 
        $oPaginate = new BxDolPaginate(array(
            'page_url' => 'javascript:void(0);',
            'count' => $iNum,
            'per_page' => $iPerPage,
            'page' => $iPage,
            'on_change_page' => 'return !loadDynamicBlock({id}, \'' . $sUrlStart . 'page={page}&per_page={per_page}\');',
        ));
 	    $sAjaxPaginate = $oPaginate->getSimplePaginate('', -1, -1, false);

        return array(
            $sRet, 
            $aMenu,
            $sAjaxPaginate,
            '');  
     }
 

     /**
     * Account block with different locations
     * @return html to display area locations in account page a block
     */  
    function serviceAccountAreaBlock () {

        if (!$this->_oDb->isAnyPublicContent())
            return '';

		$aProfileInfo = getProfileInfo($this->_iProfileId);
		$sCity = $aProfileInfo['City'];

		if(!$sCity)
			return;

        bx_import ('PageMain', $this->_aModule);
        $o = new BxLocationPageMain ($this);        
        $o->sUrlStart = BX_DOL_URL_ROOT . '?';
 
        return $o->ajaxBrowse(
            'local',
            $this->_oDb->getParam('modzzz_location_perpage_accountpage'),
			array(),
			$sCity
        );
    }

    /**
     * Account block with different locations
     * @return html to display member locations in account page a block
     */ 
    function serviceAccountPageBlock () {
  
        $aProfile = getProfileInfo($this->_iProfileId);
        bx_import ('PageMain', $this->_aModule);
        $o = new BxLocationPageMain ($this);        
        $o->sUrlStart = $GLOBALS['site']['url'] . 'member.php?';
        
		$this->_oTemplate->addCss('unit.css');

        return $o->ajaxBrowse(
            'user', 
            $this->_oDb->getParam('modzzz_location_perpage_profile'), 
            array(),
            $aProfile['NickName'],
            true,
            false 
        );
    }


    function serviceGetMemberMenuItem () {
        parent::_serviceGetMemberMenuItem (_t('_modzzz_location'), _t('_modzzz_location'), 'location.png');
    }

    function serviceGetWallPost ($aEvent) {
         return parent::_serviceGetWallPost ($aEvent, _t('_modzzz_location_wall_object'), _t('_modzzz_location_wall_added_new'));
    }

    function serviceGetSpyPost($sAction, $iObjectId = 0, $iSenderId = 0, $aExtraParams = array()) {
        return parent::_serviceGetSpyPost($sAction, $iObjectId, $iSenderId, $aExtraParams, array(
            'add' => '_modzzz_location_spy_post',
            'change' => '_modzzz_location_spy_post_change', 
            'join' => '_modzzz_location_spy_join',
            'rate' => '_modzzz_location_spy_rate',
            'commentPost' => '_modzzz_location_spy_comment',
        ));
    }

    function serviceGetSubscriptionParams ($sAction, $iEntryId) {

        $a = array (
            'change' => _t('_modzzz_location_sbs_change'),
            'commentPost' => _t('_modzzz_location_sbs_comment'),
            'rate' => _t('_modzzz_location_sbs_rate'), 
            'join' => _t('_modzzz_location_sbs_join'), 
        );

        return parent::_serviceGetSubscriptionParams ($sAction, $iEntryId, $a);
    }

    // ================================== admin actions

    function actionAdministrationPackages ($sParam1='') {
 		$sMessage = "";
  		$iPackage = (int)process_db_input($sParam1);
 
		// check actions
		if(is_array($_POST)){
		
			if(isset($_POST['action_save']) && !empty($_POST['action_save']))
			{  
 				$this->_oDb->SavePackage();
				$sMessage = _t("Successfully Saved Package");
 			} 
			if(isset($_POST['action_edit']) && !empty($_POST['action_edit']))
			{   
 				$this->_oDb->UpdatePackage();
				$sMessage = _t("Successfully Updated Package");
  			} 
			if(isset($_POST['action_delete']) && !empty($_POST['action_delete']))
			{  
 				$this->_oDb->DeletePackage();
				$sMessage = _t("Successfully Removed Package");
			} 
			if(isset($_POST['action_add']) && !empty($_POST['action_add']))
			{  
				$iPackage = 0;  
			} 
 
		}
 
		$aPackages = $this->_oDb->getPackages();
		$aPackage[] = array(
			'value' => '',
			'caption' => ''  
		);
		foreach ($aPackages as $oPackage)
		{
			$sKey = $oPackage['id'];
			$sValue = $oPackage['name'];
 
			$aPackage[] = array(
				'value' => $sKey,
				'caption' => $sValue ,
				'selected' => ($sKey == $iPackage) ? 'selected="selected"' : ''
			);
		}
		
		$sContent = $GLOBALS['oAdmTemplate']->parseHtmlByName('top_block_select.html', array(
			'name' => _t('_modzzz_location_packages'),
			'bx_repeat:items' => $aPackage,
			'location_href' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'administration/packages/'
		));


		$aPackage = $this->_oDb->getRow("SELECT * FROM `" . $this->_oDb->_sPrefix . "packages` WHERE  `id` = '$iPackage'");
		  
		$sFormName = 'packages_form';
  
	    if($iPackage){
			$sControls = BxTemplSearchResult::showAdminActionsPanel($sFormName, array(
				'action_edit' => _t('_modzzz_location_categ_btn_edit'),
				'action_delete' => _t('_modzzz_location_categ_btn_delete'), 
				'action_add' => _t('_modzzz_location_categ_btn_add')  
			), 'pathes', false);
	    }else{
			$sControls = BxTemplSearchResult::showAdminActionsPanel($sFormName, array(
				'action_save' => _t('_modzzz_location_categ_btn_save')
			), 'pathes', false);	 
	    }
 
		$aVars = array(
 			'id'=> $aPackage['id'],  
			'name' => $aPackage['name'], 
   			'price' => $aPackage['price'],
			'days' => $aPackage['days'],
			'featured' => $aPackage['featured'],
			'description' => $aPackage['description'], 
			'photo_no_select' => $aPackage['photos'] ? '' : "selected='selected'",
			'photo_yes_select' => $aPackage['photos'] ? "selected='selected'" : '',
			'video_no_select' => $aPackage['videos'] ? '' : "selected='selected'",
			'video_yes_select' => $aPackage['videos'] ? "selected='selected'" : '',
			'file_no_select' => $aPackage['files'] ? '' : "selected='selected'",
			'file_yes_select' => $aPackage['files'] ? "selected='selected'" : '',
			
			'sound_no_select' => $aPackage['sounds'] ? '' : "selected='selected'", 
			'sound_yes_select' => $aPackage['sounds'] ? "selected='selected'" : '',

			'featured_no_select' => $aPackage['featured'] ? '' : "selected='selected'", 
			'featured_yes_select' => $aPackage['featured'] ? "selected='selected'" : '',

 			'form_name' => $sFormName, 
			'controls' => $sControls,   
		);

		if($sMessage){
 			$sContent .= MsgBox($sMessage) ;
			$sContent .= "<form method=post>";
			$sContent .= BxTemplSearchResult::showAdminActionsPanel($sFormName, array(
 				'action_add' => _t('_modzzz_location_categ_btn_add'),  
			), 'pathes', false);  
			$sContent .= "</form>";
		}else{
			$sContent .= $this->_oTemplate->parseHtmlByName('admin_packages',$aVars);
		}

		return $sContent;
	}
 
    function actionAdministration ($sUrl = '',$sParam1='',$sParam2='') {

        if (!$this->isAdmin()) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }        

        $this->_oTemplate->pageStart();

        $aVars = array (
            'module_url' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri(),
        );
        $sContent = $this->_oTemplate->parseHtmlByName ('admin_links', $aVars);
        echo $this->_oTemplate->adminBlock ($sContent, _t('_modzzz_location_admin_links'));


        $aMenu = array(
            'pending_approval' => array(
                'title' => _t('_modzzz_location_menu_admin_pending_approval'), 
                'href' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'administration/pending_approval', 
                '_func' => array ('name' => 'actionAdministrationManage', 'params' => array(false)),
            ),
            'admin_entries' => array(
                'title' => _t('_modzzz_location_menu_admin_entries'), 
                'href' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'administration/admin_entries',
                '_func' => array ('name' => 'actionAdministrationManage', 'params' => array(true)),
            ),   
           'categories' => array(
                'title' => _t('_modzzz_location_menu_admin_manage_categories'), 
                'href' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'administration/categories',
                '_func' => array ('name' => 'actionAdministrationCategories', 'params' => array($sParam1)),
            ),
            'subcategories' => array(
                'title' => _t('_modzzz_location_menu_admin_manage_subcategories'), 
                'href' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'administration/subcategories',
                '_func' => array ('name' => 'actionAdministrationSubCategories', 'params' => array($sParam1,$sParam2)),
            ),  
            'create' => array(
                'title' => _t('_modzzz_location_menu_admin_add_entry'), 
                'href' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'administration/create',
                '_func' => array ('name' => 'actionAdministrationCreateEntry', 'params' => array()),
            ),
            'settings' => array(
                'title' => _t('_modzzz_location_menu_admin_settings'), 
                'href' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'administration/settings',
                '_func' => array ('name' => 'actionAdministrationSettings', 'params' => array()),
            ),
        );

        if (empty($aMenu[$sUrl]))
            $sUrl = 'pending_approval';

        $aMenu[$sUrl]['active'] = 1;
        $sContent = call_user_func_array (array($this, $aMenu[$sUrl]['_func']['name']), $aMenu[$sUrl]['_func']['params']);

        echo $this->_oTemplate->adminBlock ($sContent, _t(''), $aMenu);
        $this->_oTemplate->addCssAdmin ('admin.css');
        $this->_oTemplate->addCssAdmin ('unit.css');
        $this->_oTemplate->addCssAdmin ('main.css');
        $this->_oTemplate->addCssAdmin ('forms_extra.css'); 
        $this->_oTemplate->addCssAdmin ('forms_adv.css');        
        $this->_oTemplate->pageCodeAdmin (_t('_modzzz_location_page_title_administration'));
    }

    function actionAdministrationSettings () {
        return parent::_actionAdministrationSettings ('Location');
    }
 
    function actionAdministrationCategories ($sParam1='') {
 		$sMessage = "";
  		$iCategory = (int)process_db_input($sParam1);
 
		// check actions
		if(is_array($_POST))
		{
			if(isset($_POST['action_save']) && !empty($_POST['action_save']))
			{  
 				$this->_oDb->SaveCategory();
				$sMessage = _t("Successfully Saved Category");
 			} 
			if(isset($_POST['action_edit']) && !empty($_POST['action_edit']))
			{   
 				$this->_oDb->UpdateCategory();
				$sMessage = _t("Successfully Updated Category");
  			} 
			if(isset($_POST['action_delete']) && !empty($_POST['action_delete']))
			{  
 				$this->_oDb->DeleteCategory();
				$sMessage = _t("Successfully Removed Category");
			} 
			if(isset($_POST['action_add']) && !empty($_POST['action_add']))
			{  
				$iCategory = 0;  
			} 
			if(isset($_POST['action_sub']) && !empty($_POST['action_sub']))
			{  
				$sRedirUrl = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'administration/subcategories/'.$iCategory;
				
				header("Location: " . $sRedirUrl);
			} 		

		}
 
		$aCategories = $this->_oDb->getParentCategories();
		$aCategory[] = array(
			'value' => '',
			'caption' => ''  
		);
		foreach ($aCategories as $oCategory)
		{
			$sKey = $oCategory['id'];
			$sValue = $oCategory['name'];
   
			$aCategory[] = array(
				'value' => $sKey,
				'caption' => $sValue ,
				'selected' => ($sKey == $iCategory) ? 'selected="selected"' : ''
			);
		}
		
		$sContent = $GLOBALS['oAdmTemplate']->parseHtmlByName('top_block_select.html', array(
			'name' => _t('_modzzz_location_categories'),
			'bx_repeat:items' => $aCategory,
			'location_href' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'administration/categories/'
		));


		$aCategory = $this->_oDb->getRow("SELECT * FROM `" . $this->_oDb->_sPrefix . "categ` WHERE  `id` = '$iCategory'");
		 
		$sFormName = 'categories_form';
  
	    if($iCategory){
			$sControls = BxTemplSearchResult::showAdminActionsPanel($sFormName, array(
				'action_edit' => _t('_modzzz_location_categ_btn_edit'),
				'action_delete' => _t('_modzzz_location_categ_btn_delete'), 
				'action_add' => _t('_modzzz_location_categ_btn_add'),
				'action_sub' => _t('_modzzz_location_categ_btn_subcategories'), 
			), 'pathes', false);
	    }else{
			$sControls = BxTemplSearchResult::showAdminActionsPanel($sFormName, array(
				'action_save' => _t('_modzzz_location_categ_btn_save')
			), 'pathes', false);	 
	    }
  
		$aVars = array(
			'name' => $aCategory['name'],
			'id'=> $aCategory['id'],  
 			'form_name' => $sFormName, 
			'controls' => $sControls,   
		);

		if($sMessage){
 			$sContent .= MsgBox($sMessage) ;
			$sContent .= "<form method=post>";
			$sContent .= BxTemplSearchResult::showAdminActionsPanel($sFormName, array(
 				'action_add' => _t('_modzzz_location_categ_btn_add'),  
			), 'pathes', false);  
			$sContent .= "</form>";
		}else{
			$sContent .= $this->_oTemplate->parseHtmlByName('admin_categories',$aVars);
		}

		return $sContent;
	}

    function actionAdministrationSubCategories ($sParam1='', $sParam2='') {
 		$sMessage = "";
  		$iCategory = (int)process_db_input($sParam1);
   		$iSubCategory = (int)process_db_input($sParam2);
		$sCategoryName = $this->_oDb->getCategoryName($iCategory);
		
		if(!$iCategory){
			$sContent = MsgBox(_t('_modzzz_location_manage_subcategories_msg')); 

			return $sContent; 
		}

		// check actions
		if(is_array($_POST))
		{
			if(isset($_POST['action_save']) && !empty($_POST['action_save']))
			{  
 				$this->_oDb->SaveCategory($iCategory);
				$sMessage = _t("Successfully Saved Category");
 			} 
			if(isset($_POST['action_edit']) && !empty($_POST['action_edit']))
			{   
 				$this->_oDb->UpdateCategory();
				$sMessage = _t("Successfully Updated Category");
  			} 
			if(isset($_POST['action_delete']) && !empty($_POST['action_delete']))
			{  
 				$this->_oDb->DeleteCategory();
				$sMessage = _t("Successfully Removed Category");
			} 
			if(isset($_POST['action_add']) && !empty($_POST['action_add']))
			{  
				$iSubCategory = 0;  
			}  
		}
 
		$aSubCategories = $this->_oDb->getSubCategories($iCategory);

		foreach ($aSubCategories as $oSubCategory)
		{
			$sKey = $oSubCategory['id'];
			$sValue = $oSubCategory['name'];
   
			$aSubCategory[] = array(
				'value' => $sKey,
				'caption' => $sValue ,
				'selected' => ($sKey == $iSubCategory) ? 'selected="selected"' : ''
			);
		}
		
		$sContent = $GLOBALS['oAdmTemplate']->parseHtmlByName('top_block_select.html', array(
			'name' => $sCategoryName .': '. _t('_modzzz_location_subcategories'),
			'bx_repeat:items' => $aSubCategory,
			'location_href' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'administration/subcategories/'.$iCategory.'/'
		));


		$aCategory = $this->_oDb->getRow("SELECT * FROM `" . $this->_oDb->_sPrefix . "categ` WHERE  `id` = '$iSubCategory'");
		 
		$sFormName = 'categories_form';
 
	    if($iSubCategory){
			$sControls = BxTemplSearchResult::showAdminActionsPanel($sFormName, array(
				'action_edit' => _t('_modzzz_location_categ_btn_edit'),
				'action_delete' => _t('_modzzz_location_categ_btn_delete'), 
				'action_add' => _t('_modzzz_location_categ_btn_add'),
			), 'pathes', false);
	    }else{
			$sControls = BxTemplSearchResult::showAdminActionsPanel($sFormName, array(
				'action_save' => _t('_modzzz_location_categ_btn_save')
			), 'pathes', false);	 
	    }
  
		$aVars = array(
			'name' => $aCategory['name'],
			'id'=> $aCategory['id'],  
 			'form_name' => $sFormName, 
			'controls' => $sControls,   
		);

		if($sMessage){
 			$sContent .= MsgBox($sMessage) ;
			$sContent .= "<form method=post>";
			$sContent .= BxTemplSearchResult::showAdminActionsPanel($sFormName, array(
 				'action_add' => _t('_modzzz_location_categ_btn_add'),  
			), 'pathes', false);  
			$sContent .= "</form>";
		}else{
			$sContent .= $this->_oTemplate->parseHtmlByName('admin_categories',$aVars);
		}

		return $sContent;
	} 
  
    function actionAdministrationManage ($isAdminEntries = false) {
        return parent::_actionAdministrationManage ($isAdminEntries, '_modzzz_location_admin_delete', '_modzzz_location_admin_activate');
    }
   
    // ================================== events
 

 
    // ================================== permissions
  
    function onEventJoinRequest ($iEntryId, $iProfileId, $aDataEntry) {
        parent::_onEventJoinRequest ($iEntryId, $iProfileId, $aDataEntry, 'modzzz_location_join_request', BX_LOCATION_MAX_FANS);
    }

    function onEventJoinReject ($iEntryId, $iProfileId, $aDataEntry) {
        parent::_onEventJoinReject ($iEntryId, $iProfileId, $aDataEntry, 'modzzz_location_join_reject');
    }

    function onEventFanRemove ($iEntryId, $iProfileId, $aDataEntry) {        
        parent::_onEventFanRemove ($iEntryId, $iProfileId, $aDataEntry, 'modzzz_location_fan_remove');
    }

    function onEventFanBecomeAdmin ($iEntryId, $iProfileId, $aDataEntry) {        
        parent::_onEventFanBecomeAdmin ($iEntryId, $iProfileId, $aDataEntry, 'modzzz_location_fan_become_admin');
    }

    function onEventAdminBecomeFan ($iEntryId, $iProfileId, $aDataEntry) {        
        parent::_onEventAdminBecomeFan ($iEntryId, $iProfileId, $aDataEntry, 'modzzz_location_admin_become_fan');
    }

    function onEventJoinConfirm ($iEntryId, $iProfileId, $aDataEntry) {
        parent::_onEventJoinConfirm ($iEntryId, $iProfileId, $aDataEntry, 'modzzz_location_join_confirm');
    }

    function isAllowedJoin (&$aDataEntry) {
        if (!$this->_iProfileId) 
            return false;
        return $this->_oPrivacy->check('join', $aDataEntry['id'], $this->_iProfileId);
    }

    function isAllowedView ($aDataEntry, $isPerformAction = false) {

        // admin and owner always have access
        if ($this->isAdmin() || $aDataEntry['author_id'] == $this->_iProfileId) 
            return true;

        // check admin acl
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_LOCATION_VIEW_LOCATION, $isPerformAction);
        if ($aCheck[CHECK_ACTION_RESULT] != CHECK_ACTION_RESULT_ALLOWED)
            return false;
 
        // check user group  
        $isAllowed =  $this->_oPrivacy->check('view', $aDataEntry['id'], $this->_iProfileId);   
		return $isAllowed && $this->_isAllowedViewByMembership ($aDataEntry); 

    }

    function _isAllowedViewByMembership (&$aDataEntry) { 
        if (!$aDataEntry['membership_view_filter']) return true;
        require_once(BX_DIRECTORY_PATH_INC . 'membership_levels.inc.php');
        $aMembershipInfo = getMemberMembershipInfo($this->_iProfileId);
 
		if($aMembershipInfo['DateExpires']) 
			return $aDataEntry['membership_view_filter'] == $aMembershipInfo['ID'] && $aMembershipInfo['DateStarts'] < time() && $aMembershipInfo['DateExpires'] > time() ? true : false;
		else
			return $aDataEntry['membership_view_filter'] == $aMembershipInfo['ID'] && $aMembershipInfo['DateStarts'] < time() ? true : false; 
    }
  
    function isAllowedBrowse ($isPerformAction = false) {
        if ($this->isAdmin()) 
            return true;
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_LOCATION_BROWSE, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;
    }

    function isAllowedSearch ($isPerformAction = false) {
        if ($this->isAdmin()) 
            return true;
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_LOCATION_SEARCH, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;
    }

    function isAllowedAdd ($isPerformAction = false) {
        if ($this->isAdmin()) 
            return true;
        if (!$GLOBALS['logged']['member']) 
            return false;
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_LOCATION_ADD_LOCATION, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;
    } 

    function isAllowedSubAdd ($aDataEntry, $isPerformAction = false) {

		if ($this->isAdmin())
            return true;
 
		if(getParam('modzzz_location_any_add_subsection') != 'on'){
 			if(!$this->isEntryAdmin($aDataEntry))
				return false;
		}

        // check acl
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_LOCATION_ADD_LOCATION, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;
    } 

    function isAllowedSubEdit ($aDataEntry, $aSubDataEntry, $isPerformAction = false) {

        if ($this->isAdmin()) 
            return true;

        if ($GLOBALS['logged']['member'] && $aDataEntry['author_id'] == $this->_iProfileId && isProfileActive($this->_iProfileId)) 
            return true;

        if ($GLOBALS['logged']['member'] && $aSubDataEntry['author_id'] == $this->_iProfileId && isProfileActive($this->_iProfileId)) 
            return true;
 
        // check acl
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_LOCATION_EDIT_ANY_LOCATION, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;
    } 
  
    function isAllowedSubDelete ($aDataEntry, $aSubDataEntry, $isPerformAction = false) {

        if ($this->isAdmin()) 
            return true;

        if ($GLOBALS['logged']['member'] && $aDataEntry['author_id'] == $this->_iProfileId && isProfileActive($this->_iProfileId)) 
            return true;

        if ($GLOBALS['logged']['member'] && $aSubDataEntry['author_id'] == $this->_iProfileId && isProfileActive($this->_iProfileId)) 
            return true;

        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_LOCATION_DELETE_ANY_LOCATION, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;
    }    
  
    function isAllowedEdit ($aDataEntry, $isPerformAction = false) {

        if ($this->isAdmin() || ($GLOBALS['logged']['member'] && $aDataEntry['author_id'] == $this->_iProfileId && isProfileActive($this->_iProfileId))) 
            return true;

        // check acl
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_LOCATION_EDIT_ANY_LOCATION, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;
    } 

    function isAllowedMarkAsFeatured ($aDataEntry, $isPerformAction = false) {
        if ($this->isAdmin()) 
            return true;
        $this->_defineActions();
        $aCheck = checkAction($this->_iProfileId, BX_LOCATION_MARK_AS_FEATURED, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;        
    }
  
    function isAllowedDelete (&$aDataEntry, $isPerformAction = false) {
        if ($this->isAdmin() || ($GLOBALS['logged']['member'] && $aDataEntry['author_id'] == $this->_iProfileId && isProfileActive($this->_iProfileId))) 
            return true;
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_LOCATION_DELETE_ANY_LOCATION, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;
    }     
 
    function isAllowedSendInvitation (&$aDataEntry) {
        return true;
    }
 
    function isAllowedShare (&$aDataEntry) {
        return true;
    }
 

    function isAllowedRate(&$aDataEntry) {        
        if ($this->isAdmin())
            return true;
        return $this->_oPrivacy->check('rate', $aDataEntry['id'], $this->_iProfileId);        
    }

    function isAllowedComments(&$aDataEntry) {
        if (!$this->_iProfileId) 
            return false;        
        if ($this->isAdmin())
            return true;
        return $this->_oPrivacy->check('comment', $aDataEntry['id'], $this->_iProfileId);
    }
    
    function isAllowedViewFans(&$aDataEntry) {        
        if ($this->isAdmin())
            return true;
        return $this->_oPrivacy->check('view_fans', $aDataEntry['id'], $this->_iProfileId);        
    }
 
	function isAllowedViewReviews(&$aDataEntry) {
 
        return $this->isAllowedView($aDataEntry);
    }
 
    function isAllowedUploadPhotos(&$aDataEntry) {
       
		if (!$this->_iProfileId) 
            return false;  
	 
        if ($this->isAdmin())
            return true; 
     
        if (!$this->isMembershipEnabledForImages())
            return false;
 
        return $this->_oPrivacy->check('upload_photos', $aDataEntry['id'], $this->_iProfileId);
    }

    function isAllowedUploadVideos(&$aDataEntry) {
        if (!$this->_iProfileId) 
            return false;        
        if ($this->isAdmin())
            return true; 
        if (!$this->isMembershipEnabledForVideos())
            return false;                
        return $this->_oPrivacy->check('upload_videos', $aDataEntry['id'], $this->_iProfileId);
    }

    function isAllowedUploadSounds(&$aDataEntry) {
        if (!$this->_iProfileId) 
            return false;        
        if ($this->isAdmin())
            return true; 
        if (!$this->isMembershipEnabledForSounds())
            return false;                        
        return $this->_oPrivacy->check('upload_sounds', $aDataEntry['id'], $this->_iProfileId);
    }

    function isAllowedUploadFiles(&$aDataEntry) {
        if (!$this->_iProfileId) 
            return false;        
        if ($this->isAdmin())
            return true; 
        if (!$this->isMembershipEnabledForFiles())
            return false;                        
        return $this->_oPrivacy->check('upload_files', $aDataEntry['id'], $this->_iProfileId);
    }
	
    function isAllowedCreatorCommentsDeleteAndEdit (&$aDataEntry, $isPerformAction = false) {
        if ($this->isAdmin()) return true;        
        if (!$GLOBALS['logged']['member'] || $aDataEntry['author_id'] != $this->_iProfileId)
            return false;
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_LOCATION_COMMENTS_DELETE_AND_EDIT, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;
    }

    function isAllowedManageAdmins($aDataEntry) {
        if (($GLOBALS['logged']['member'] || $GLOBALS['logged']['admin']) && $aDataEntry['author_id'] == $this->_iProfileId && isProfileActive($this->_iProfileId))
            return true;
        return false;
    }
   
	function isPermalinkEnabled() {
		$bEnabled = isset($this->_isPermalinkEnabled) ? $this->_isPermalinkEnabled : ($this->_isPermalinkEnabled = (getParam('permalinks_location') == 'on'));
		 
        return $bEnabled;
    }


    function _defineActions () {
        defineMembershipActions(array( 'location view location', 'location browse', 'location search', 'location add location', 'location comments delete and edit', 'location edit any location', 'location delete any location', 'location mark as featured', 'location approve location', 'location add review'));
    }

 
    function _browseMy (&$aProfile) {        
        parent::_browseMy ($aProfile, _t('_modzzz_location_page_title_my_location'));
    } 
	
    function onEventCreate ($iEntryId, $sStatus, $aDataEntry = array()) {
  
		$this->serviceUpdateProfileLocation ($iEntryId);

		if ('approved' == $sStatus) {
            $this->reparseTags ($iEntryId);
            $this->reparseCategories ($iEntryId);
        }

        $this->_oDb->createForum ($aDataEntry, $this->_oDb->getProfileNickNameById($this->_iProfileId));

 		$oAlert = new BxDolAlerts($this->_sPrefix, 'add', $iEntryId, $this->_iProfileId, array('Status' => $sStatus));
		$oAlert->alert();
    }

    function onEventChanged ($iEntryId, $sStatus) {

		$this->serviceUpdateProfileLocation ($iEntryId);

        $this->reparseTags ($iEntryId);
        $this->reparseCategories ($iEntryId);
 
		$oAlert = new BxDolAlerts($this->_sPrefix, 'change', $iEntryId, $this->_iProfileId, array('Status' => $sStatus));
		$oAlert->alert();
    } 

    function getTagLinks($sTagList, $sType = 'tag', $sDivider = ' ') {
        if (strlen($sTagList)) {
            $aTags = explode($sDivider, $sTagList);
            foreach ($aTags as $iKey => $sValue) {
                $sValue   = trim($sValue, ','); 
                $aRes[$sValue] = $sValue;
            }
        }
        return $aRes;
    }

   function parseTags($s)
    {
        return $this->_parseAnything($s, ',', BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'browse/tag/');
    }

    function parseCategories($s)
    {
        return $this->_parseAnything($s, CATEGORIES_DIVIDER, BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'browse/category/');
    }

    function _parseAnything($s, $sDiv, $sLinkStart, $sClassName = '')
    {
        $sRet = '';
        $a = explode ($sDiv, $s);
        $sClass = $sClassName ? 'class="'.$sClassName.'"' : '';
        
        foreach ($a as $sName)
            $sRet .= '<a '.$sClass.' href="' . $sLinkStart . urlencode(title2uri($sName)) . '">'.$sName.'</a>&#160';
        
        return $sRet;
    }

	/*[begin] map integration*/


    function actionMapEdit ($iEntryID) {

		$aDataEntry = $this->_oDb->getEntryById($iEntryID);
       
		$GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);


        $aLocation = $iEntryID ? $this->_oDb->getProfileById($iEntryID) : false;
        if (!$iEntryID || !$this->isAllowedEditOwnLocation($iEntryID, $aLocation)) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        } 
  
        if (!($aDataEntry = $this->_oDb->getEntryByIdAndOwner($iEntryID, $this->_iProfileId, $this->isAdmin()))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }

        $this->_oTemplate->pageStart();
 
        modzzz_location_import ('PageEdit');
        $oPage = new BxLocationPageEdit ($this, $aLocation);
        echo $oPage->getCode();

        $this->_oTemplate->addJs ('http://www.google.com/jsapi?key=' . getParam('modzzz_location_key'));
        $this->_oTemplate->addJs ('BxMap.js');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('search.css');
        $this->_oTemplate->pageCode(_t('_modzzz_location_edit'), false, false);
    }  


    function actionSaveDataProfile ($iEntryID, $iZoom, $sMapType, $fLat, $fLng, $sMapClassInstanceName, $sAddress, $sCountry) {

        $aLocation = $iEntryID ? $this->_oDb->getProfileById($iEntryID) : false;
        if (!$iEntryID || !$this->isAllowedEditOwnLocation($iEntryID, $aLocation))
            return;


        if (!$aLocation && ('null' == $fLat || 'null' == $fLng))
            return;
        
        $fLat = 'null' != $fLat ? (float)$fLat : $aLocation['lat'];
        $fLng = 'null' != $fLng ? (float)$fLng : $aLocation['lng'];
        $iZoom = 'null' != $iZoom ? (int)$iZoom : ($aLocation ? $aLocation['zoom'] : -1);
        $sMapType = 'null' != $sMapType ? $sMapType : ($aLocation ? $aLocation['type'] : '');
        $sAddress = 'null' != $sAddress ? process_db_input($sAddress, BX_TAGS_STRIP) : '';
        $sCountry = 'null' != $sCountry ? process_db_input($sCountry, BX_TAGS_STRIP) : '';

        switch ($sMapType) {
            case 'normal':
            case 'satellite':
            case 'hybrid':
                break;
            default:
                $sMapType = 'normal';
        }

        if ($this->_oDb->insertProfileLocation ($this->_iProfileId,$iEntryID, $fLat, $fLng, $iZoom, $sMapType, $sAddress, $sCountry)) {
            $this->onEventProfileLocationManuallyUpdated ($iEntryID, array ('lat' => $fLat, 'lng' => $fLng, 'zoom' => $iZoom, 'map_type' => $sMapType, 'address' => $sAddress, 'country' => $sCountry));
            echo 1;
        }
    }
  
    function actionGetDataProfile ($iId, $sMapClassInstanceName) {
        
        $iProfileId = $iId;
        $r = $this->_oDb->getProfileById($iProfileId);
        if (!$r || !$this->isAllowedViewLocation ($iProfileId, $r))
            return;        

        if (!$iId) {
            $aRet = array ();
            $aRet[] = array (
                    'lat' => $r['lat'],
                    'lng' => $r['lng'],
                    'data' => '',
                    'icon' => array ('w' => 0, 'h' => 0, 'sw' => 0, 'sh' => 0, 'sd' => '', 'url' => ''),
                );

            $oParser = new Services_JSON();
            echo $oParser->encode($aRet);
            return;
        }

        $sImage = '';
        if ($r['thumb']) {
            $a = array ('ID' => $this->_oDb->getAuthorById($iId), 'Avatar' => $r['thumb']);
            $aImage = BxDolService::call('photos', 'get_image', array($a, 'browse'), 'Search');
            $sImage = $aImage['no_image'] ? '' : $aImage['file'];
        } 


        $aVars = array (
			 
			'bx_if:address1' => array( 
				'condition' =>  strlen(trim($r['address1'])),
				'content' => array(
					'address1' => trim($r['address1']), 
				) 
			), 
			'bx_if:address2' => array( 
				'condition' =>  strlen(trim($r['address2'])),
				'content' => array(
					'address2' => trim($r['address2']), 
				) 
			),  
			'thumb' => $sImage ? $sImage : $this->_oTemplate->getIconUrl('no-photo.png'), 
			'url_flag' => genFlagUrl($r['country']),
			'country' => _t($GLOBALS['aPreValues']['Country'][$r['country']]['LKey']),
			'city' => trim($r['city']) ? $r['city'] : _t('_modzzz_location_unknown_city'), 
		);
        $sHtml = $this->_oTemplate->parseHtmlByName ('popup_profile', $aVars);

        $aIconJSON = false;
        /*
		if ($r['thumb']) {

			include_once (BX_DIRECTORY_PATH_MODULES . 'boonex/avatar/include.php');
	        $sAvatarImg = BX_AVA_URL_USER_AVATARS . $r['Avatar'] . BX_AVA_EXT;
            $aIconJSON = array ('w' => 32, 'h' => 32, 'sw' => 34, 'sh' => 34, 'sd' => '1', 'url' => $sAvatarImg);
        }
		*/
        if (!$aIconJSON) {
            $sIconUser = $this->_oTemplate->getIconUrl ('user.png');
            $aIconJSON = array ('w' => 16, 'h' => 16, 'sw' => 24, 'sh' => 16, 'sd' => '', 'url' => $sIconUser);
        }

        $aRet = array ();
        $aRet[] = array (
                'lat' => $r['lat'],
                'lng' => $r['lng'],
                'data' => $sHtml,
                'icon' => $aIconJSON, 
            );

        $oParser = new Services_JSON();
        echo $oParser->encode($aRet);        
    }

    function actionGetHtmlProfiles ($sFilter) {        

        $aProfiles = $this->_getProfilesByFilter ($sFilter);
        if (!$aProfiles) {
            echo MsgBox(_t('_Empty'));
            return;
        }

        if (!$aProfiles) {
            echo MsgBox(_t('_Empty'));
            return;
        }

        bx_import ('BxTemplSearchProfile');
        $oBxTemplSearchProfile = new BxTemplSearchProfile();
        foreach ($aProfiles as $r) {
            $aProfileInfo = $this->_oDb->getProfileInfo($r['id']);
            $sProfiles .= $oBxTemplSearchProfile->displaySearchUnit($aProfileInfo);
        }

        echo $GLOBALS['oFunctions']->centerContent($sProfiles, '.searchrow_block_simple');
    }

    function actionGetData ($iZoom, $fLatMin, $fLatMax, $fLngMin, $fLngMax, $sMapClassInstanceName, $sFilter = '') {

        $fLatMin = (float)$fLatMin;
        $fLatMax = (float)$fLatMax;
        $fLngMin = (float)$fLngMin;
        $fLngMax = (float)$fLngMax;

        if ($sFilter) {
            echo $this->_getProfilesData('filter', $sFilter, 0, 0);
            return;
        }

        $iZoom = (int)$iZoom;
        if ($iZoom >= BX_LOCATION_ZOOM_COUNTRIES && $iZoom < BX_LOCATION_ZOOM_CITIES) {
            echo $this->_getCountriesData($fLatMin, $fLatMax, $fLngMin, $fLngMax, $sMapClassInstanceName);
        } elseif ($iZoom >= BX_LOCATION_ZOOM_CITIES && $iZoom < BX_LOCATION_ZOOM_PROFILES) {
            echo $this->_getCitiesData($fLatMin, $fLatMax, $fLngMin, $fLngMax, $sMapClassInstanceName);
        } elseif ($iZoom >= BX_LOCATION_ZOOM_PROFILES) {
            echo $this->_getProfilesData($fLatMin, $fLatMax, $fLngMin, $fLngMax);
        }
    }

    function _getProfilesData ($fLatMin, $fLatMax, $fLngMin, $fLngMax) {

        $sIconUser = $this->_oTemplate->getIconUrl ('user.png');
        $sIconGroup = $this->_oTemplate->getIconUrl ('group.png');

        if ('filter' == $fLatMin) {
            $a = $this->_getProfilesByFilter ($fLatMax); 
        } else {
            $a = $this->_oDb->getProfilesByBounds((float)$fLatMin, (float)$fLatMax, (float)$fLngMin, (float)$fLngMax);
        }

        $aa = array ();
        foreach ($a as $r) {
            $sKey = $r['lat'].'x'.$r['lng'];
            $aVars = array ('thumb' => get_member_thumbnail($r['id'], 'none', true));
            $aa[$sKey][] = array (
                'lat' => $r['lat'],
                'lng' => $r['lng'],
                'username' => $r['NickName'],
                'html' => $this->_oTemplate->parseHtmlByName ('popup_profile', $aVars),
            );
        }

        $aRet = array();
        foreach ($aa as $k => $a) {
            $sHtml = '';
            $aUsernames = array ();
            foreach ($a as $r) {
                $sHtml .= $r['html'];
                $aUsernames[] = $r['username'];
            }
            $aVars = array ('content' => $sHtml);
            $aRet[] = array (
                'lat' => $r['lat'],
                'lng' => $r['lng'],                
                'usernames' => $aUsernames,
                'data' => $this->_oTemplate->parseHtmlByName ('popup_profiles', $aVars),                
                'icon' => array ('w' => 16, 'h' => 16, 'sw' => 24, 'sh' => 16, 'sd' => '', 'url' => (count($a) > 1 ? $sIconGroup : $sIconUser)),
            );
        }
        $oParser = new Services_JSON();
        return $oParser->encode($aRet);
    }

    function _getCitiesData ($fLatMin, $fLatMax, $fLngMin, $fLngMax, $sMapClassInstanceName) {

        $sIconUrl = $this->_oTemplate->getIconUrl ('city.png');

        $a = $this->_oDb->getCitiesByBounds((float)$fLatMin, (float)$fLatMax, (float)$fLngMin, (float)$fLngMax);

        if (!preg_match('/^[A-Za-z0-9]+$/', $sMapClassInstanceName))
            return '';        

        $aRet = array();
        foreach ($a as $r) {
            $aVars = array (
                'url_flag' => genFlagUrl($r['country']),
                'country' => _t($GLOBALS['aPreValues']['Country'][$r['country']]['LKey']),
                'city' => trim($r['city']) ? $r['city'] : _t('_modzzz_location_unknown_city'),
                'num' => sprintf(_t('_modzzz_location_%d_members'), $r['num']),
                'lat' => $r['lat'],
                'lng' => $r['lng'],
                'zoom' => BX_LOCATION_ZOOM_PROFILES,
                'map_instance_name' => $sMapClassInstanceName,
            );
            $sHtml = $this->_oTemplate->parseHtmlByName ('popup_city', $aVars);
            $aRet[] = array (
                'lat' => $r['lat'],
                'lng' => $r['lng'],
                'data' => $sHtml,
                'icon' => array ('w' => 48, 'h' => 28, 'sw' => 72, 'sh' => 48, 'sd' => '', 'url' => $sIconUrl),
            );
        }
        $oParser = new Services_JSON();
        return $oParser->encode($aRet);
    }

    function _getCountriesData ($fLatMin, $fLatMax, $fLngMin, $fLngMax, $sMapClassInstanceName) {

        $a = $this->_oDb->getCountriesByBounds((float)$fLatMin, (float)$fLatMax, (float)$fLngMin, (float)$fLngMax);

        if (!preg_match('/^[A-Za-z0-9]+$/', $sMapClassInstanceName))
            return '';

        $aRet = array();
        foreach ($a as $r) {
            $sFlagUrl = genFlagUrl($r['country']);
            $aVars = array (
                'url_flag' => $sFlagUrl, 
                'country' => _t($GLOBALS['aPreValues']['Country'][$r['country']]['LKey']), 
                'num' => sprintf(_t('_modzzz_location_%d_members'), $r['num']),
                'lat' => $r['lat'],
                'lng' => $r['lng'],
                'zoom' => BX_LOCATION_ZOOM_CITIES,
                'map_instance_name' => $sMapClassInstanceName,
            );
            $sHtml = $this->_oTemplate->parseHtmlByName ('popup_country', $aVars);
            $aRet[] = array (
                'lat' => $r['lat'],
                'lng' => $r['lng'],
                'data' => $sHtml,
                'icon' => array ('w' => 18, 'h' => 12, 'sw' => 20, 'sh' => 14, 'sd' => 1, 'url' => $sFlagUrl),
            );
        }
        $oParser = new Services_JSON();
        return $oParser->encode($aRet);
    }

    // ================================== admin actions

    function actionClearTable ($sTable,  $isClearFailedOnly = true) {

        if (!$this->isAdmin()) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }

        switch ($sTable) {
            case 'countries':
                $this->_oDb->clearCountries ($isClearFailedOnly ? true : false);
                $this->_oTemplate->displayMsg('Countries locations has been cleared');
                break;
            case 'cities':
                $this->_oDb->clearCities ($isClearFailedOnly ? true : false);
                $this->_oTemplate->displayMsg('Cities locations has been cleared');
                break;
            default:
                $this->_oTemplate->displayPageNotFound ();
        }
    }

    function actionUpdateCountries ($iLimit = 4, $iDelay = 6) { 

        if (!$this->isAdmin()) {
            $this->_oTemplate->displayAccessDenied ();
            return;            
        }

        $iLimit = (int)$iLimit;
        $iDelay = (int)$iDelay;

        $a = $this->_oDb->getUndefinedCountries ($iLimit);
        if ($a) {
            foreach ($a as $sCountryCode => $sCountryName) {
                $a = $this->_geocode ($sCountryName, $sCountryCode);                                
                if ($a) {                                        
                    $this->_oDb->insertCountryLocation ($sCountryCode, $a[0], $a[1]);
                } else {
                    $this->_oDb->insertCountryLocation ($sCountryCode, 0, 0, 1);
                }
                $this->onEventGeolocateCountry ($sCountryCode, array ('lat' => (isset($a[0]) ? $a[0] : false), 'lng' => (isset($a[1]) ? $a[1] : false)));
                if ($iDelay)
                    sleep ($iDelay);
            }

            $aVars = array (
                'refresh' => 1,
                'msg' => 'Countries update is in progress, please wait...',
            );
            echo $this->_oTemplate->parseHtmlByName ('updating', $aVars);
        } else {
            $this->_oTemplate->displayMsg('Countries locations update has been completed');
        }
    }

    function actionUpdateCities ($iLimit = 4, $iDelay = 6) {

        if (!$this->isAdmin()) {
            $this->_oTemplate->displayAccessDenied ();
            return;            
        }

        $iLimit = (int)$iLimit;
        $iDelay = (int)$iDelay;

        $a = $this->_oDb->getUndefinedCities ($iLimit);
        if ($a) {

            foreach ($a as $sCountryCode => $sCity) {
                $this->_updateCityLocation($iDelay, $sCity, $sCountryCode);
            }

            $aVars = array (
                'refresh' => 1,
                'msg' => 'Cities update is in progress, please wait...',
            );
            echo $this->_oTemplate->parseHtmlByName ('updating', $aVars);
        } else {
            $this->_oTemplate->displayMsg('Cities locations update has been completed');
        }
    }

    function actionUpdateProfiles ($iLimit = 4, $iDelay = 6) {

        if (!$this->isAdmin()) {
            $this->_oTemplate->displayAccessDenied ();
            return;            
        }

        $iLimit = (int)$iLimit;
        $iDelay = (int)$iDelay;

        $a = $this->_oDb->getUndefinedProfiles ($iLimit);
        if ($a) {
            foreach ($a as $iId => $r) {
                $this->_updateProfileLocation ($iDelay, $r);
            }

            $aVars = array (
                'refresh' => 1,
                'msg' => 'Locations update is in progress, please wait...',
            );
            echo $this->_oTemplate->parseHtmlByName ('updating', $aVars);
        } else {
            $this->_oTemplate->displayMsg('Locations locations update has been completed');
        }
    }
  
    function onEventGeolocateProfile ($iProfileId, $aLocation) {
		//
    }

    function onEventGeolocateCity ($sCity, $aLocation) {
		//
    }

    function onEventGeolocateCountry ($sCountryCode, $aLocation) {
		//
    }

    function onEventProfileLocationManuallyUpdated ($iProfileId, $aLocation) {
		//
    }
 
    // ================================== service actions

    /**
     * Get profile location by user id
     * @param $iProfileId user's id 
     * @param $iViewerProfileId viewer profile id
     * @param $isClearFailedOnly check privacy settings before returning location
     * @return array with location info on success, false on error, -1 if access denied
     */ 
    function serviceGetLocation ($iProfileId, $iViewerProfileId = 0, $isCheckPrivacy = true) {
        $iProfileId = (int)$iProfileId;
        $iViewerProfileId = (int)$iViewerProfileId;
        if ($isCheckPrivacy) {
            if (!$iViewerProfileId)
                $iViewerProfileId = $this->_iProfileId; 
            if (!$this->_oPrivacy->check('view_location', $iProfileId, $iViewerProfileId))
                return -1;
        }

        $aLocation = $iProfileId ? $this->_oDb->getProfileById($iProfileId) : false;
        if (!$aLocation)
            return false;

        if (-1 == $aLocation['zoom'])
            $aLocation['zoom'] = 5;

        if (!$aLocation['type'])
            $aLocation['type'] = 'normal';

        return $aLocation;
    }

    /**
     * Edit location block
     * @param $iEntryId user's id which location is edited
     * @return html with clickable map
     */ 
    function serviceEditLocation ($iEntryId) {

        $iEntryId = (int)$iEntryId;

        $aLocation = $iEntryId ? $this->_oDb->getProfileById($iEntryId) : false;
        if (!$aLocation)
            return false;

        $fLat = false;
        $fLng = false;
        $iZoom = false;
        $sMapType = false;

        if ($aLocation) {
            $fLat = $aLocation['lat'];
            $fLng = $aLocation['lng'];
            $iZoom = $aLocation['zoom'];
            $sMapType = $aLocation['type'];
        }

        if (false === $fLat || false === $fLng) {
            $aProfile = $this->_oDb->getProfileInfo($iEntryId);
            $aLocationCountry = $this->_oDb->getCountryByCode($aProfile['country'], false);
            $fLat = $aLocationCountry['lat'];
            $fLng = $aLocationCountry['lng'];
            $iZoom = BX_LOCATION_ZOOM_CITIES;            
        }

        if (false === $iZoom || -1 == $iZoom)
            $iZoom = 5;

        if (!$sMapType)
            $sMapType = 'normal';


        $aVars = array (
            'msg_incorrect_google_key' => _t('_modzzz_location_msg_incorrect_google_key'),
            'loading' => _t('_loading ...'),
            'map_control' => 'small',
            'map_is_type_control' => 1 ,
            'map_is_scale_control' => 0,
            'map_is_overview_control' => 0,
            'map_is_dragable' => 1, 
			'map_type' => $sMapType,
            'map_lat' => $fLat,
            'map_lng' => $fLng,
            'map_zoom' => $iZoom,
            'suffix' => 'Edit',
            'subclass' => 'modzzz_location_profile',
            'data_url' => BX_DOL_URL_MODULES . "?r=location/get_data_profile/0/{instance}/{ts}",
            'save_data_url' => BX_DOL_URL_MODULES . "?r=location/save_data_profile/{$iEntryId}/{zoom}/{map_type}/{lat}/{lng}/{instance}/{address}/{country}/{ts}",
            'save_location_url' => '',
            'shadow_url' => '',
        );
        return  $this->_oTemplate->parseHtmlByName('map', $aVars);
    }
  
    /**
     * Removes any geocoding information associated with profile
     * @param $iProfileId user's id which location going to be removed
     * @return true if location existed and was deleted, false on error or location didn't exist
     */ 
    function serviceDeleteProfileLocation ($iProfileId) {
        return $this->_oDb->deleteLocation((int)$iProfileId);
    }

    /**
     * Update profile's location
     * @param $iProfileId user's id which location going to be removed
     * @return true if position was successfully geocoded, and false if doesn't
     */     
    function serviceUpdateProfileLocation ($iProfileId) {
        $iProfileId = (int)$iProfileId;
        $a = $this->_oDb->getProfileInfo($iProfileId);
        if ($this->_updateProfileLocation(0, $a)) {
            if (!$this->_oDb->isCityLocationExists($a['country'], process_db_input($a['city'], BX_TAGS_NO_ACTION, BX_SLASHES_NO_ACTION)))
                $this->_updateCityLocation(0, $a['city'], $a['country']);
            return true;
        }
        return false;
    }

    /**
     * Update profile's location manually
     * @param $iProfileId user's id which location going to be updated 
     * @param $fLat latitude
     * @param $gLng longitude
     * @param $iZoom zoom level
     * @param $sMapType map type (hybrid, satellite or standard)
     * @param $sCountry 2 letters country code
     * @param $sAddress address string
     * @return true if position was successfully updated, and false if doesn't
     */     
    function serviceUpdateProfileLocationManually ($iEntryId, $fLat, $fLng, $iZoom, $sMapType, $sCountry, $sAddress) {
        $a = $this->_oDb->getProfileInfo((int)$iEntryId);
        $aLocationOld = $this->_oDb->getProfileById((int)$iEntryId);

        if (!$iZoom)
            $iZoom = $aLocationOld && $aLocationOld['zoom'] ? $aLocationOld['zoom'] : -1;
        switch ($sMapType) {
        case 'hybrid':
        case 'satellite':
        case 'standard':
        break;
        default:
            $sMapType = 'standard'; 
        }

        $fLat = (float)$fLat;
        $fLng = (float)$fLng;
        $iZoom = (int)$iZoom;

        $iRet = $this->_oDb->insertProfileLocation (
			$this->_iProfileId,    
			$iEntryId, 
            $fLat, 
            $fLng, 
            $iZoom, 
            $sMapType, 
            '', // address 
            '', // country 
            $aLocationOld && $aLocationOld['allow_view_location_to'] ? $aLocationOld['allow_view_location_to'] : BX_LOCATION_DEFAULT_PRIVACY);

        if ($iRet) {
            $this->onEventProfileLocationManuallyUpdated ($iEntryId, array ('lat' => $fLat, 'lng' => $fLng, 'zoom' => $iZoom, 'map_type' => $sMapType, 'address' => '', 'country' => ''));
            return true;
        }

        return false;
    }
 
 
    // ================================== permissions  

    function isAllowedEditOwnLocation ($iEntryID, &$aLocation) {
        if(!$iEntryID) 
            return false;
        if (!$aLocation || $aLocation['id'] == $iEntryID) {
            return true;
        }        
        return false;
    }

    function isAllowedViewLocation ($iEntryID, &$aLocation) {
        if (!$aLocation) 
            return false;
		
		$aDataEntry = $this->_oDb->getEntryById($iEntryID);
 
        if ($aDataEntry['author_id'] == $this->_iProfileId || $this->isAdmin())
            return true;
 
        return $this->_oMapPrivacy->check('view_location', $iEntryID, $this->_iProfileId);  
    }
  
    function isAdmin () {
        return $GLOBALS['logged']['admin'] || $GLOBALS['logged']['moderator'];
    }             

    // ================================== other 

    function _geocode ($sAddress, $sCountryCode = '') {

        $iRet = 404;

        $sAddress = rawurlencode($sAddress);
        $sUrl = "http://maps.google.com/maps/geo";

        $s = bx_file_get_contents($sUrl, array(
            'q' => $sAddress,
            'output' => 'xml',
            'key' => getParam('modzzz_location_key')
        ));
        
        if (preg_match ('/<code>(\d+)<\/code>/', $s, $m))
        {
            $iRet = $m[1];
            if (200 != $iRet) return false;

            if (preg_match_all ('/<CountryNameCode>([A-Za-z]+)<\/CountryNameCode>/', $s, $mCountry) &&
                preg_match_all ('/<coordinates>([0-9,\.-]+)<\/coordinates>/', $s, $mCoord))
            {
                if (isset($mCountry[1]) && is_array($mCountry[1]))
                    $mCountry = $mCountry[1];

                foreach ($mCountry AS $k => $v)
                {
                    if (!$sCountryCode || ($sCountryCode && 0 == strcasecmp($sCountryCode, $v))) 
                    {
                        // Parse coordinate string
                        list ($fLongitude, $fLatitude, $fAltitude) = explode(",", $mCoord[1][$k]);
                        return array ($fLatitude, $fLongitude, $v);
                    }
                }
            }
        }
        return false;
    }

    function _updateCityLocation($iDelay, &$sCity, $sCountryCode) {

        $iDelay = (int)$iDelay;
        if ($iDelay) sleep ($iDelay);
        $a = $this->_geocode ($sCity . ' ' . $sCountryCode, $sCountryCode);        
        if ($a) {
            $this->_oDb->insertCityLocation ($sCountryCode, process_db_input($sCity, BX_TAGS_NO_ACTION, BX_SLASHES_NO_ACTION), $a[0], $a[1]);
            $bRet = true;
        } else {
            $this->_oDb->insertCityLocation ($sCountryCode, process_db_input($sCity, BX_TAGS_NO_ACTION, BX_SLASHES_NO_ACTION), 0, 0, 1);
            $bRet = false;
        }
        $this->onEventGeolocateCity ($sCity, array ('lat' => (isset($a[0]) ? $a[0] : false), 'lng' => (isset($a[1]) ? $a[1] : false), 'country' => $sCountryCode));
        return $bRet;
    }

    function _updateProfileLocation($iDelay, &$r) {

        $iDelay = (int)$iDelay;

        $iId = (int)$r['id'];
        $a = false;
 
		$sState = (($r['country']=='US') && $r['state']) ? $r['state'] : '';
 
        //$sAddressField = getParam('modzzz_location_address_field');
        if (isset ($r['address1'])) {
            if ($iDelay) sleep ($iDelay);
			 
			if($sState)
				$a = $this->_geocode ($r['address1'] . ' ' . $r['city'] . ' ' . $sState . ' ' . $r['country'], $r['country']);
			else
				$a = $this->_geocode ($r['address1'] . ' ' . $r['city'] . ' ' . $r['country'], $r['country']);
        }

        if (!$a && isset ($r['zip'])) { 
            if ($iDelay) sleep ($iDelay);
            $a = $this->_geocode ($r['zip'] . ' ' . $r['country'], $r['country']); 
        }

        if (!$a) { 
            if ($iDelay) sleep ($iDelay);

			if($sState)
				$a = $this->_geocode ($r['city'] . ' ' . $sState . ' ' . $r['country'], $r['country']);
			else
				$a = $this->_geocode ($r['city'] . ' ' . $r['country'], $r['country']);

        }
        
        if ($a) {
            $this->_oDb->insertProfileLocation ($r['author_id'], $iId, $a[0], $a[1], -1, '', process_db_input($r['city'] . ', ' . $r['country'], BX_TAGS_NO_ACTION, BX_SLASHES_NO_ACTION), process_db_input($r['country'], BX_TAGS_NO_ACTION, BX_SLASHES_NO_ACTION), BX_LOCATION_DEFAULT_PRIVACY);
            $bRet = true;
        } else {
            $this->_oDb->insertProfileLocation ($r['author_id'], $iId, 0, 0, -1, '', '', '', BX_LOCATION_DEFAULT_PRIVACY, 1);
            $bRet = false;
        }          
        $this->onEventGeolocateProfile ($iId, array ('lat' => (isset($a[0]) ? $a[0] : false), 'lng' => (isset($a[1]) ? $a[1] : false), 'country' => $sCountryCode));
        return $bRet;
    }

    function _saveLocationByPrefix ($sPrefix, $iZoom, $sMapType, $fLat, $fLng) {

        if (!$this->isAdmin()) {
            echo 'Access denied';
            return;
        }

        if ($iZoom = (int)$iZoom)
            setParam($sPrefix . '_zoom', $iZoom);

        switch ($sMapType) {
            case 'normal':
            case 'satellite':
            case 'hybrid':
                setParam($sPrefix . '_map_type', $sMapType);
        }                

        if ($fLat = (float)$fLat)
            setParam($sPrefix . '_lat', $fLat);

        if ($fLng = (float)$fLng)
            setParam($sPrefix . '_lng', $fLng);

        echo 'ok';
    }    

    function _saveLocationForm ($sSuffix, $sMap) {

        if (!preg_match('/^[A-Za-z0-9]+$/', $sSuffix))
            return '';

        $aCustomForm = array(
            
            'form_attrs' => array(
                'name'     => "modzzz_location_save_location_{$sSuffix}",
                'onsubmit'   => "return glBxMap{$sSuffix}.saveLocation();",
                'method'   => 'post',
            ),

            'inputs' => array(

                'Map' => array (
                    'type' => 'custom',
                    'content' => "<div class=\"modzzz_location_form_map\">$sMap</div>",
                    'name' => 'Map',
                    'caption' => _t('_modzzz_location_admin_map'),
                ),

                'Submit' => array (
                    'type' => 'submit',
                    'name' => 'submit_form',
                    'value' => _t('_modzzz_location_admin_save_location'),
                    'colspan' => true,
                ),                            
            ),
        );

        $f = new BxTemplFormView ($aCustomForm);
        return $f->getCode();
    }

    function _getProfilesByFilter ($sFilter) {

        $aGetParams = unserialize(base64_decode($sFilter));            
        if ($aGetParams && is_array($aGetParams))
            $aGetParams = $_REQUEST = $_GET = array_merge ($_REQUEST, $aGetParams);

        bx_import('BxDolProfileFields');
        $oPF = new BxDolProfileFields(9);
        $aRequestParams = $oPF->collectSearchRequestParams();

        bx_import ('BxTemplProfileView');
        $oProfileGenerator = new BxBaseProfileGenerator((int)$_COOKIE['memberID']);
        list ($aWhere, $sJoin, $sPossibleOrder) = $oProfileGenerator->GenSqlConditions($oPF->aBlocks, $aRequestParams);

        $iPage = isset($aGetParams['page']) && (int)$aGetParams['page'] > 0 ? (int)$aGetParams['page'] : 1;
        $iPerPage = isset($aGetParams['per_page']) && (int)$aGetParams['per_page'] > 0 ? (int)$aGetParams['per_page'] : getParam('modzzz_location_per_page'); 
        $iStart = ($iPage - 1) * $iPerPage;            
        
        $sQuery = 'SELECT DISTINCT `' . $this->_oDb->_sPrefix . 'main`.`id`, `' . $this->_oDb->_sPrefix . 'main`.`thumb`, `' . $this->_oDb->_sPrefix . 'main`.`title` as `NickName`, `m`.`id`, `m`.`lat`, `m`.`lng`
            FROM `' . $this->_oDb->_sPrefix . 'main` 
            INNER JOIN `' . $this->_oDb->_sPrefix . 'profiles` AS `m` ON (`' . $this->_oDb->_sPrefix . 'main` .`id` = `m`.`id`) 
            ' . $sJoin . ' 
            WHERE ' . implode( ' AND ', $aWhere ) . ' AND `m`.`failed` = 0 ' . $sPossibleOrder . " 
            LIMIT $iStart, $iPerPage";

        // ID is ambiguous
        $sQuery = str_replace (' `id`', ' `' . $this->_oDb->_sPrefix . 'main`.`id`', $sQuery);
        
        $aProfiles = $GLOBALS['MySQL']->getAll($sQuery);

        return $aProfiles;
    } 
	/*[end] map integration*/
 
    function actionLocal ($sCountry='', $sState='') { 
        $this->_oTemplate->pageStart();
        bx_import ('PageLocal', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'PageLocal';
        $oPage = new $sClass ($this, $sCountry, $sState);
        echo $oPage->getCode();
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('unit.css');
         $this->_oTemplate->pageCode(_t('_modzzz_location_page_title_local'), false, false);
    } 



    function isMembershipEnabledForImages () {
        return ($this->_isMembershipEnabledFor ('BX_PHOTOS_ADD') && $this->_isMembershipEnabledFor ('BX_LOCATION_PHOTOS_ADD'));
    }

    function isMembershipEnabledForVideos () {
        return $this->_isMembershipEnabledFor ('BX_VIDEOS_ADD');
        return ($this->_isMembershipEnabledFor ('BX_VIDEOS_ADD') && $this->_isMembershipEnabledFor ('BX_LOCATION_VIDEOS_ADD')); 
    }

    function isMembershipEnabledForSounds () {
        return ($this->_isMembershipEnabledFor ('BX_SOUNDS_ADD') && $this->_isMembershipEnabledFor ('BX_LOCATION_SOUNDS_ADD'));
    }

    function isMembershipEnabledForFiles () {
        return ($this->_isMembershipEnabledFor ('BX_FILES_ADD') && $this->_isMembershipEnabledFor ('BX_LOCATION_FILES_ADD'));
    }
 
    function _isMembershipEnabledFor ($sMembershipActionConstant) { 
        defineMembershipActions (array('photos add', 'sounds add', 'videos add', 'files add', 'location photos add', 'location sounds add', 'location videos add', 'location files add'));
		if (!defined($sMembershipActionConstant))
			return false;
		$aCheck = checkAction($_COOKIE['memberID'], constant($sMembershipActionConstant));
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;
    }  

     /**
     * forum permissions
     * @param $iMemberId profile id
     * @param $iForumId forum id
     * @return array with permissions
     */ 
    function serviceGetForumPermission($iMemberId, $iForumId) {

        $iMemberId = (int)$iMemberId;
        $iForumId = (int)$iForumId;

        $aFalse = array ( // default permissions, for visitors for example
            'admin' => 0,
            'read' => 1,
            'post' => 0,
        );

        if (!($aForum = $this->_oDb->getForumById ($iForumId))) {    
			return $aFalse;
        }
  
        if (!($aDataEntry = $this->_oDb->getEntryById ($aForum['entry_id']))){
 			return $aFalse;
		}
 
        $aTrue = array (
            'admin' => $aDataEntry[$this->_oDb->_sFieldAuthorId] == $iMemberId || $this->isAdmin() ? 1 : 0, // author is admin
            'read' => $this->isAllowedPostInForum ($aDataEntry, $iMemberId) ? 1 : 0,
            'post' => $this->isAllowedPostInForum ($aDataEntry, $iMemberId) ? 1 : 0,
        );
  
        return $aTrue;
    }
 
     function isAllowedPostInForum(&$aDataEntry, $iProfileId = -1) {
        if (-1 == $iProfileId)
            $iProfileId = $this->_iProfileId;
        return $this->isAdmin() || $this->isEntryAdmin($aDataEntry) || $this->_oPrivacy->check('post_in_forum', $aDataEntry['id'], $iProfileId);
    }

    function isAllowedManageFans($aDataEntry) {
        return $this->isEntryAdmin($aDataEntry);
    }

    function isFan($aDataEntry, $iProfileId = 0, $isConfirmed = true) {
        if (!$iProfileId)
            $iProfileId = $this->_iProfileId;
        return $this->_oDb->isFan ($aDataEntry['id'], $iProfileId, $isConfirmed) ? true : false;
    }

    function isEntryAdmin($aDataEntry, $iIdProfile = 0) {
        if (!$iIdProfile)
            $iIdProfile = $this->_iProfileId;
        return ($this->isAdmin() || $aDataEntry['author_id'] == $iIdProfile);
    }
 
	/******[BEGIN] Event functions **************************/ 
    function actionEvent ($sAction, $sIdUri) {
		switch($sAction){
			case 'add': 
				$this->actionEventAdd ($sIdUri, '_modzzz_location_page_title_event_add');
			break;
			case 'edit':
				$this->actionEventEdit ($sIdUri, '_modzzz_location_page_title_event_edit');
			break;
			case 'delete':
				$this->actionEventDelete ($sIdUri, _t('_modzzz_location_msg_location_was_event_deleted'));
			break;
			case 'view':
				$this->actionEventView ($sIdUri, _t('_modzzz_location_msg_pending_event_approval')); 
			break; 
			case 'browse':
				return $this->actionEventBrowse ($sIdUri, '_modzzz_location_page_title_event_browse'); 
			break;  
		}
	}
    
    function actionEventBrowse ($sUri, $sTitle) {
       
        if (!($aDataEntry = $this->_oDb->getEntryByUri($sUri))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }		
		
		$this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);

        bx_import ('EventPageBrowse', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'EventPageBrowse';
        $oPage = new $sClass ($this, $sUri);
        echo $oPage->getCode();
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('unit.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry['title']), false, false);  
    }
 
    function actionEventView ($sUri, $sMsgPendingApproval) {

		$aEventEntry = $this->_oDb->getEventEntryByUri($sUri);
		$iEntryId = (int)$aEventEntry['location_id'];
 
        if (!($aDataEntry = $this->_oDb->getEntryById($iEntryId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }
 
        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aEventEntry[$this->_oDb->_sFieldTitle] .' - '. $aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);

        bx_import ('EventPageView', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'EventPageView';
        $oPage = new $sClass ($this, $aEventEntry);

        if ($aDataEntry[$this->_oDb->_sFieldStatus] == 'pending') {
            $aVars = array ('msg' => $sMsgPendingApproval); // this product is pending approval, please wait until it will be activated
            echo $this->_oTemplate->parseHtmlByName ('pending_approval_plank', $aVars);
        }

        echo $oPage->getCode();

        bx_import('EventCmts', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'EventCmts';
        $oCmts = new $sClass ($this->_sPrefix, 0);

        $this->_oTemplate->setPageDescription (substr(strip_tags($aEventEntry[$this->_oDb->_sFieldDescription]), 0, 255));
        $this->_oTemplate->addPageKeywords ($aEventEntry[$this->_oDb->_sFieldTags]);

        $this->_oTemplate->addCss ('view.css');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('entry_view.css');
        $this->_oTemplate->addCss ('unit_fan.css');
 
		$sPageTitle = $aEventEntry[$this->_oDb->_sFieldTitle] .' | '. $aDataEntry[$this->_oDb->_sFieldTitle];

        $this->_oTemplate->pageCode($sPageTitle, false, false);

        bx_import ('BxDolViews');
        new BxDolViews($this->_oDb->_sEventPrefix, $aDataEntry[$this->_oDb->_sFieldId]);
    }


    function actionEventEdit ($iEntryId, $sTitle) { 

        $iEntryId = (int)$iEntryId;

		$aEventEntry = $this->_oDb->getEventEntryById($iEntryId);
		$iEventId = (int)$aEventEntry['location_id'];
  
        if (!($aDataEntry = $this->_oDb->getEntryById($iEventId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }
  
        if (!$this->isAllowedSubEdit($aDataEntry, $aEventEntry)) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }

        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);

        bx_import ('EventFormEdit', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'EventFormEdit';
        $oForm = new $sClass ($this, $aEventEntry[$this->_oDb->_sFieldAuthorId], $iEventId,  $iEntryId, $aEventEntry);
  
        $oForm->initChecker($aEventEntry);

        if ($oForm->isSubmittedAndValid ()) {
 
            $this->_oDb->_sTableMain = 'event_main';
			$this->_oDb->_sTableMediaPrefix = $this->_oDb->_sTableEventMediaPrefix;
 
            if ($oForm->update ($iEntryId, $aValsAdd)) {
  
				$oForm->processMedia($iEntryId, $this->_iProfileId);
  
                $this->isAllowedEdit($aDataEntry, true); // perform action

                $this->onEventSubProfileChanged ('event', $iEntryId, $sStatus);
                header ('Location:' . BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'event/view/' . $aEventEntry[$this->_oDb->_sFieldUri]);
                exit;

            } else {

                echo MsgBox(_t('_Error Occured'));
                
            }            

        } else {

            echo $oForm->getCode ();

        }

        $this->_oTemplate->addJs ('main.js');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('forms_extra.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry['title']));  
    }

    function actionEventDelete ($iEventId, $sMsgSuccess) {

		$aEventEntry = $this->_oDb->getEventEntryById($iEventId);
		$iEntryId = (int)$aEventEntry['location_id'];
  
        if (!($aDataEntry = $this->_oDb->getEntryByIdAndOwner($iEntryId, $this->_iProfileId, $this->isAdmin()))) {
            echo MsgBox(_t('_sys_request_page_not_found_cpt')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }
 
        if (!$this->isAllowedSubDelete($aDataEntry, $aEventEntry) || 0 != strcasecmp($_SERVER['REQUEST_METHOD'], 'POST')) {
            echo MsgBox(_t('_Access denied')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }
  
        if ($this->_oDb->deleteEventByIdAndOwner($iEventId, $iEntryId, $this->_iProfileId, $this->isAdmin())) {
            $this->isAllowedDelete($aDataEntry, true); // perform action
            $this->onEventEventDeleted ($iEntryId, $aDataEntry);            
            $sRedirect = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri];
  
            $sJQueryJS = genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div', $sRedirect);
            echo MsgBox(_t($sMsgSuccess)) . $sJQueryJS;
            exit;
        }

        echo MsgBox(_t('_Error Occured')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
        exit;
    }
 
    function actionEventAdd ($iEventId, $sTitle) {
  
        if (!$this->isAllowedAdd()) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }

		if (!($aDataEntry = $this->_oDb->getEntryById($iEventId))) {
			$this->_oTemplate->displayPageNotFound ();
			return;
		}	

        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);


        $this->_addEventForm($iEventId);

        $this->_oTemplate->addJs ('main.js');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('forms_extra.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry['title']));  
    }
 
    function _addEventForm ($iEventId) { 
 
        bx_import ('EventFormAdd', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'EventFormAdd';
        $oForm = new $sClass ($this, $this->_iProfileId, $iEventId);
        $oForm->initChecker();

        if ($oForm->isSubmittedAndValid ()) {
 
			$sStatus = 'approved';

            $this->_oDb->_sTableMain = 'event_main';
			$this->_oDb->_sTableMediaPrefix = $this->_oDb->_sTableEventMediaPrefix;
 
            $aValsAdd = array (
                $this->_oDb->_sFieldCreated => time(),
                $this->_oDb->_sFieldUri => $oForm->generateUri(),
                $this->_oDb->_sFieldStatus => $sStatus,
				$this->_oDb->_sFieldAuthorId => $this->_iProfileId 
            );                        
 
            $iEntryId = $oForm->insert ($aValsAdd);
 
            if ($iEntryId) {

                $this->isAllowedAdd(true); // perform action                 
 
				$oForm->processMedia($iEntryId, $this->_iProfileId); 
	  
                $aDataEntry = $this->_oDb->getEventEntryById($iEntryId);
                $this->onEventSubProfileCreate('event', $iEntryId, $sStatus, $aDataEntry);
   
				$sRedirectUrl = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'event/view/' . $aDataEntry[$this->_oDb->_sFieldUri];
			  
                header ('Location:' . $sRedirectUrl);
                exit;

            } else {

                MsgBox(_t('_Error Occured'));
            }
                         
        } else { 
            echo $oForm->getCode (); 
        }
    }
 
    function onEventEventDeleted ($iEntryId, $aDataEntry = array()) {

        // delete associated tags and categories 
		$this->reparseSubProfileTags ('event', $iEntryId);
		$this->reparseSubProfileCategories ('event', $iEntryId); 

        // delete votings
        bx_import('EventVoting', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'EventVoting';
        $oVoting = new $sClass ($this->_oDb->_sEventPrefix, 0, 0);
        $oVoting->deleteVotings ($iEntryId);

        // delete comments 
        bx_import('EventCmts', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'EventCmts';
        $oCmts = new $sClass ($this->_oDb->_sEventPrefix, $iEntryId);
        $oCmts->onObjectDelete ();

        // delete views
        bx_import ('BxDolViews');
        $oViews = new BxDolViews($this->_oDb->_sEventPrefix, $iEntryId, false);
        $oViews->onObjectDelete();

 
        // arise alert
		//$oAlert = new BxDolAlerts($this->_sPrefix, 'delete', $iEntryId, $this->_iProfileId);
		//$oAlert->alert();
    }        


    /*******[END - Event Functions] ******************************/

	/******[BEGIN] Shop functions **************************/ 
    function actionShop ($sAction, $sIdUri) {
		switch($sAction){
			case 'add': 
				$this->actionShopAdd ($sIdUri, '_modzzz_location_page_title_shop_add');
			break;
			case 'edit':
				$this->actionShopEdit ($sIdUri, '_modzzz_location_page_title_shop_edit');
			break;
			case 'delete':
				$this->actionShopDelete ($sIdUri, _t('_modzzz_location_msg_location_was_shop_deleted'));
			break;
			case 'view':
				$this->actionShopView ($sIdUri, _t('_modzzz_location_msg_pending_shop_approval')); 
			break; 
			case 'browse':
				return $this->actionShopBrowse ($sIdUri, '_modzzz_location_page_title_shop_browse'); 
			break;  
		}
	}
    
    function actionShopBrowse ($sUri, $sTitle) {
       
        if (!($aDataEntry = $this->_oDb->getEntryByUri($sUri))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }		
		
		$this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);

        bx_import ('ShopPageBrowse', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'ShopPageBrowse';
        $oPage = new $sClass ($this, $sUri);
        echo $oPage->getCode();
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('unit.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry['title']), false, false);  
    }
 
    function actionShopView ($sUri, $sMsgPendingApproval) {

		$aShopEntry = $this->_oDb->getShopEntryByUri($sUri);
		$iEntryId = (int)$aShopEntry['location_id'];
 
        if (!($aDataEntry = $this->_oDb->getEntryById($iEntryId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }
 
        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aShopEntry[$this->_oDb->_sFieldTitle] .' - '. $aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);
 
        bx_import ('ShopPageView', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'ShopPageView';
        $oPage = new $sClass ($this, $aShopEntry);

        if ($aDataEntry[$this->_oDb->_sFieldStatus] == 'pending') {
            $aVars = array ('msg' => $sMsgPendingApproval); // this product is pending approval, please wait until it will be activated
            echo $this->_oTemplate->parseHtmlByName ('pending_approval_plank', $aVars);
        }

        echo $oPage->getCode();

        bx_import('ShopCmts', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'ShopCmts';
        $oCmts = new $sClass ($this->_sPrefix, 0);

        $this->_oTemplate->setPageDescription (substr(strip_tags($aShopEntry[$this->_oDb->_sFieldDescription]), 0, 255));
        $this->_oTemplate->addPageKeywords ($aShopEntry[$this->_oDb->_sFieldTags]);

        $this->_oTemplate->addCss ('view.css');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('entry_view.css');
        $this->_oTemplate->addCss ('unit_fan.css');

		$sPageTitle = $aShopEntry[$this->_oDb->_sFieldTitle] .' | '. $aDataEntry[$this->_oDb->_sFieldTitle];
 
        $this->_oTemplate->pageCode($sPageTitle, false, false);

        bx_import ('BxDolViews');
        new BxDolViews($this->_oDb->_sShopPrefix, $aDataEntry[$this->_oDb->_sFieldId]);
    }


    function actionShopEdit ($iEntryId, $sTitle) { 

        $iEntryId = (int)$iEntryId;

		$aShopEntry = $this->_oDb->getShopEntryById($iEntryId);
		$iShopId = (int)$aShopEntry['location_id'];
  
        if (!($aDataEntry = $this->_oDb->getEntryById($iShopId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }
  
        if (!$this->isAllowedSubEdit($aDataEntry, $aShopEntry)) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }

        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);

        bx_import ('ShopFormEdit', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'ShopFormEdit';
        $oForm = new $sClass ($this, $aShopEntry[$this->_oDb->_sFieldAuthorId], $iShopId,  $iEntryId, $aShopEntry);
  
        $oForm->initChecker($aShopEntry);

        if ($oForm->isSubmittedAndValid ()) {
 
            $this->_oDb->_sTableMain = 'shop_main';
			$this->_oDb->_sTableMediaPrefix = $this->_oDb->_sTableShopMediaPrefix;


            if ($oForm->update ($iEntryId, $aValsAdd)) {
  
				$oForm->processMedia($iEntryId, $this->_iProfileId);
  
                $this->isAllowedEdit($aDataEntry, true); // perform action

                $this->onEventSubProfileChanged ('shop', $iEntryId, $sStatus);
                header ('Location:' . BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'shop/view/' . $aShopEntry[$this->_oDb->_sFieldUri]);
                exit;

            } else {

                echo MsgBox(_t('_Error Occured'));
                
            }            

        } else {

            echo $oForm->getCode ();

        }

        $this->_oTemplate->addJs ('main.js');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('forms_extra.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry['title']));  
    }

    function actionShopDelete ($iShopId, $sMsgSuccess) {

		$aShopEntry = $this->_oDb->getShopEntryById($iShopId);
		$iEntryId = (int)$aShopEntry['location_id'];
  
        if (!($aDataEntry = $this->_oDb->getEntryByIdAndOwner($iEntryId, $this->_iProfileId, $this->isAdmin()))) {
            echo MsgBox(_t('_sys_request_page_not_found_cpt')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }

        if (!$this->isAllowedSubDelete($aDataEntry, $aShopEntry) || 0 != strcasecmp($_SERVER['REQUEST_METHOD'], 'POST')) {
            echo MsgBox(_t('_Access denied')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }

        if ($this->_oDb->deleteShopByIdAndOwner($iShopId, $iEntryId, $this->_iProfileId, $this->isAdmin())) {
            $this->isAllowedDelete($aDataEntry, true); // perform action
            $this->onEventShopDeleted ($iEntryId, $aDataEntry);            
            $sRedirect = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri];
  
            $sJQueryJS = genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div', $sRedirect);
            echo MsgBox(_t($sMsgSuccess)) . $sJQueryJS;
            exit;
        }

        echo MsgBox(_t('_Error Occured')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
        exit;
    }
 
    function actionShopAdd ($iShopId, $sTitle) {
  
        if (!$this->isAllowedAdd()) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }


		if (!($aDataEntry = $this->_oDb->getEntryById($iShopId))) {
			$this->_oTemplate->displayPageNotFound ();
			return;
		}	

        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);


        $this->_addShopForm($iShopId);

        $this->_oTemplate->addJs ('main.js');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('forms_extra.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry['title']));  
    }
 
    function _addShopForm ($iShopId) { 
 
        bx_import ('ShopFormAdd', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'ShopFormAdd';
        $oForm = new $sClass ($this, $this->_iProfileId, $iShopId);
        $oForm->initChecker();

        if ($oForm->isSubmittedAndValid ()) {
 
			$sStatus = 'approved';

            $this->_oDb->_sTableMain = 'shop_main';
			$this->_oDb->_sTableMediaPrefix = $this->_oDb->_sTableShopMediaPrefix;
 
            $aValsAdd = array (
                $this->_oDb->_sFieldCreated => time(),
                $this->_oDb->_sFieldUri => $oForm->generateUri(),
                $this->_oDb->_sFieldStatus => $sStatus,
				$this->_oDb->_sFieldAuthorId => $this->_iProfileId 
            );                        
 
            $iEntryId = $oForm->insert ($aValsAdd);
 
            if ($iEntryId) {

                $this->isAllowedAdd(true); // perform action                 
 
				$oForm->processMedia($iEntryId, $this->_iProfileId); 
	  
                $aDataEntry = $this->_oDb->getShopEntryById($iEntryId);
                $this->onEventSubProfileCreate('shop', $iEntryId, $sStatus, $aDataEntry);
   
				$sRedirectUrl = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'shop/view/' . $aDataEntry[$this->_oDb->_sFieldUri];
			  
                header ('Location:' . $sRedirectUrl);
                exit;

            } else {

                MsgBox(_t('_Error Occured'));
            }
                         
        } else { 
            echo $oForm->getCode (); 
        }
    }
 
    function onEventShopDeleted ($iEntryId, $aDataEntry = array()) {

        // delete associated tags and categories 
		$this->reparseSubProfileTags ('shop', $iEntryId);
		$this->reparseSubProfileCategories ('shop', $iEntryId); 

        // delete votings
        bx_import('ShopVoting', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'ShopVoting';
        $oVoting = new $sClass ($this->_oDb->_sShopPrefix, 0, 0);
        $oVoting->deleteVotings ($iEntryId);

        // delete comments 
        bx_import('ShopCmts', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'ShopCmts';
        $oCmts = new $sClass ($this->_oDb->_sShopPrefix, $iEntryId);
        $oCmts->onObjectDelete ();

        // delete views
        bx_import ('BxDolViews');
        $oViews = new BxDolViews($this->_oDb->_sShopPrefix, $iEntryId, false);
        $oViews->onObjectDelete();

 
        // arise alert
		//$oAlert = new BxDolAlerts($this->_sPrefix, 'delete', $iEntryId, $this->_iProfileId);
		//$oAlert->alert();
    }        
 
    /*******[END - Shop Functions] ******************************/

	/******[BEGIN] Transport functions **************************/ 
    function actionTransport ($sAction, $sIdUri) {
		switch($sAction){
			case 'add': 
				$this->actionTransportAdd ($sIdUri, '_modzzz_location_page_title_transport_add');
			break;
			case 'edit':
				$this->actionTransportEdit ($sIdUri, '_modzzz_location_page_title_transport_edit');
			break;
			case 'delete':
				$this->actionTransportDelete ($sIdUri, _t('_modzzz_location_msg_location_was_transport_deleted'));
			break;
			case 'view':
				$this->actionTransportView ($sIdUri, _t('_modzzz_location_msg_pending_transport_approval')); 
			break; 
			case 'browse':
				return $this->actionTransportBrowse ($sIdUri, '_modzzz_location_page_title_transport_browse'); 
			break;  
		}
	}
    
    function actionTransportBrowse ($sUri, $sTitle) {
       
        if (!($aDataEntry = $this->_oDb->getEntryByUri($sUri))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }		
		
		$this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);

        bx_import ('TransportPageBrowse', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'TransportPageBrowse';
        $oPage = new $sClass ($this, $sUri);
        echo $oPage->getCode();
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('unit.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry['title']), false, false);  
    }
 
    function actionTransportView ($sUri, $sMsgPendingApproval) {

		$aTransportEntry = $this->_oDb->getTransportEntryByUri($sUri);
		$iEntryId = (int)$aTransportEntry['location_id'];
 
        if (!($aDataEntry = $this->_oDb->getEntryById($iEntryId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }
 
        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aTransportEntry[$this->_oDb->_sFieldTitle] .' - '. $aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);
 
        bx_import ('TransportPageView', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'TransportPageView';
        $oPage = new $sClass ($this, $aTransportEntry);

        if ($aDataEntry[$this->_oDb->_sFieldStatus] == 'pending') {
            $aVars = array ('msg' => $sMsgPendingApproval); // this product is pending approval, please wait until it will be activated
            echo $this->_oTemplate->parseHtmlByName ('pending_approval_plank', $aVars);
        }

        echo $oPage->getCode();

        bx_import('TransportCmts', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'TransportCmts';
        $oCmts = new $sClass ($this->_sPrefix, 0);

        $this->_oTemplate->setPageDescription (substr(strip_tags($aTransportEntry[$this->_oDb->_sFieldDescription]), 0, 255));
        $this->_oTemplate->addPageKeywords ($aTransportEntry[$this->_oDb->_sFieldTags]);

        $this->_oTemplate->addCss ('view.css');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('entry_view.css');
        $this->_oTemplate->addCss ('unit_fan.css');

		$sPageTitle = $aTransportEntry[$this->_oDb->_sFieldTitle] .' | '. $aDataEntry[$this->_oDb->_sFieldTitle];

        $this->_oTemplate->pageCode($sPageTitle, false, false);
 
        bx_import ('BxDolViews');
        new BxDolViews($this->_oDb->_sTransportPrefix, $aDataEntry[$this->_oDb->_sFieldId]);
    }


    function actionTransportEdit ($iEntryId, $sTitle) { 

        $iEntryId = (int)$iEntryId;

		$aTransportEntry = $this->_oDb->getTransportEntryById($iEntryId);
		$iTransportId = (int)$aTransportEntry['location_id'];
  
        if (!($aDataEntry = $this->_oDb->getEntryById($iTransportId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }
  
        if (!$this->isAllowedSubEdit($aDataEntry, $aTransportEntry)) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }

        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);

        bx_import ('TransportFormEdit', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'TransportFormEdit';
        $oForm = new $sClass ($this, $aTransportEntry[$this->_oDb->_sFieldAuthorId], $iTransportId,  $iEntryId, $aTransportEntry);
  
        $oForm->initChecker($aTransportEntry);

        if ($oForm->isSubmittedAndValid ()) {
 
            $this->_oDb->_sTableMain = 'transport_main';
			$this->_oDb->_sTableMediaPrefix = $this->_oDb->_sTableTransportMediaPrefix;
 
            if ($oForm->update ($iEntryId, $aValsAdd)) {
  
				$oForm->processMedia($iEntryId, $this->_iProfileId);
  
                $this->isAllowedEdit($aDataEntry, true); // perform action

                $this->onEventSubProfileChanged ('transport', $iEntryId, $sStatus);
                header ('Location:' . BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'transport/view/' . $aTransportEntry[$this->_oDb->_sFieldUri]);
                exit;

            } else {

                echo MsgBox(_t('_Error Occured'));
                
            }            

        } else {

            echo $oForm->getCode ();

        }

        $this->_oTemplate->addJs ('main.js');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('forms_extra.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry['title']));  
    }

    function actionTransportDelete ($iTransportId, $sMsgSuccess) {

		$aTransportEntry = $this->_oDb->getTransportEntryById($iTransportId);
		$iEntryId = (int)$aTransportEntry['location_id'];
  
        if (!($aDataEntry = $this->_oDb->getEntryByIdAndOwner($iEntryId, $this->_iProfileId, $this->isAdmin()))) {
            echo MsgBox(_t('_sys_request_page_not_found_cpt')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }

        if (!$this->isAllowedSubDelete($aDataEntry, $aTransportEntry) || 0 != strcasecmp($_SERVER['REQUEST_METHOD'], 'POST')) {
            echo MsgBox(_t('_Access denied')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }

        if ($this->_oDb->deleteTransportByIdAndOwner($iTransportId, $iEntryId, $this->_iProfileId, $this->isAdmin())) {
            $this->isAllowedDelete($aDataEntry, true); // perform action
            $this->onEventTransportDeleted ($iEntryId, $aDataEntry);            
            $sRedirect = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri];
  
            $sJQueryJS = genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div', $sRedirect);
            echo MsgBox(_t($sMsgSuccess)) . $sJQueryJS;
            exit;
        }

        echo MsgBox(_t('_Error Occured')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
        exit;
    }
 
    function actionTransportAdd ($iTransportId, $sTitle) {
  
        if (!$this->isAllowedAdd()) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }


		if (!($aDataEntry = $this->_oDb->getEntryById($iTransportId))) {
			$this->_oTemplate->displayPageNotFound ();
			return;
		}	

        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);


        $this->_addTransportForm($iTransportId);

        $this->_oTemplate->addJs ('main.js');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('forms_extra.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry['title']));  
    }
 
    function _addTransportForm ($iTransportId) { 
 
        bx_import ('TransportFormAdd', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'TransportFormAdd';
        $oForm = new $sClass ($this, $this->_iProfileId, $iTransportId);
        $oForm->initChecker();

        if ($oForm->isSubmittedAndValid ()) {
 
			$sStatus = 'approved';

            $this->_oDb->_sTableMain = 'transport_main';
			$this->_oDb->_sTableMediaPrefix = $this->_oDb->_sTableTransportMediaPrefix;
 
            $aValsAdd = array (
                $this->_oDb->_sFieldCreated => time(),
                $this->_oDb->_sFieldUri => $oForm->generateUri(),
                $this->_oDb->_sFieldStatus => $sStatus,
				$this->_oDb->_sFieldAuthorId => $this->_iProfileId 
            );                        
 
            $iEntryId = $oForm->insert ($aValsAdd);
 
            if ($iEntryId) {

                $this->isAllowedAdd(true); // perform action                 
 
				$oForm->processMedia($iEntryId, $this->_iProfileId); 
	  
                $aDataEntry = $this->_oDb->getTransportEntryById($iEntryId);
                $this->onEventSubProfileCreate('transport', $iEntryId, $sStatus, $aDataEntry);
   
				$sRedirectUrl = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'transport/view/' . $aDataEntry[$this->_oDb->_sFieldUri];
			  
                header ('Location:' . $sRedirectUrl);
                exit;

            } else {

                MsgBox(_t('_Error Occured'));
            }
                         
        } else { 
            echo $oForm->getCode (); 
        }
    }
  
    function onEventTransportDeleted ($iEntryId, $aDataEntry = array()) {

        // delete associated tags and categories 
		$this->reparseSubProfileTags ('transport', $iEntryId);
		$this->reparseSubProfileCategories ('transport', $iEntryId); 
 
        // delete votings
        bx_import('TransportVoting', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'TransportVoting';
        $oVoting = new $sClass ($this->_oDb->_sTransportPrefix, 0, 0);
        $oVoting->deleteVotings ($iEntryId);

        // delete comments 
        bx_import('TransportCmts', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'TransportCmts';
        $oCmts = new $sClass ($this->_oDb->_sTransportPrefix, $iEntryId);
        $oCmts->onObjectDelete ();

        // delete views
        bx_import ('BxDolViews');
        $oViews = new BxDolViews($this->_oDb->_sTransportPrefix, $iEntryId, false);
        $oViews->onObjectDelete();

 
        // arise alert
		//$oAlert = new BxDolAlerts($this->_sPrefix, 'delete', $iEntryId, $this->_iProfileId);
		//$oAlert->alert();
    }        


    /*******[END - Transport Functions] ******************************/


	/******[BEGIN] Nightlife functions **************************/ 
    function actionNightlife ($sAction, $sIdUri) {
		switch($sAction){
			case 'add': 
				$this->actionNightlifeAdd ($sIdUri, '_modzzz_location_page_title_nightlife_add');
			break;
			case 'edit':
				$this->actionNightlifeEdit ($sIdUri, '_modzzz_location_page_title_nightlife_edit');
			break;
			case 'delete':
				$this->actionNightlifeDelete ($sIdUri, _t('_modzzz_location_msg_location_was_nightlife_deleted'));
			break;
			case 'view':
				$this->actionNightlifeView ($sIdUri, _t('_modzzz_location_msg_pending_nightlife_approval')); 
			break; 
			case 'browse':
				return $this->actionNightlifeBrowse ($sIdUri, '_modzzz_location_page_title_nightlife_browse'); 
			break;  
		}
	}
    
    function actionNightlifeBrowse ($sUri, $sTitle) {
       
        if (!($aDataEntry = $this->_oDb->getEntryByUri($sUri))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }		
		
		$this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);

        bx_import ('NightlifePageBrowse', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'NightlifePageBrowse';
        $oPage = new $sClass ($this, $sUri);
        echo $oPage->getCode();
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('unit.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry['title']), false, false);  
    }
 
    function actionNightlifeView ($sUri, $sMsgPendingApproval) {

		$aNightlifeEntry = $this->_oDb->getNightlifeEntryByUri($sUri);
		$iEntryId = (int)$aNightlifeEntry['location_id'];
 
        if (!($aDataEntry = $this->_oDb->getEntryById($iEntryId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }
 
        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aNightlifeEntry[$this->_oDb->_sFieldTitle] .' - '. $aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);
 
        bx_import ('NightlifePageView', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'NightlifePageView';
        $oPage = new $sClass ($this, $aNightlifeEntry);

        if ($aDataEntry[$this->_oDb->_sFieldStatus] == 'pending') {
            $aVars = array ('msg' => $sMsgPendingApproval); // this product is pending approval, please wait until it will be activated
            echo $this->_oTemplate->parseHtmlByName ('pending_approval_plank', $aVars);
        }

        echo $oPage->getCode();

        bx_import('NightlifeCmts', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'NightlifeCmts';
        $oCmts = new $sClass ($this->_sPrefix, 0);

        $this->_oTemplate->setPageDescription (substr(strip_tags($aNightlifeEntry[$this->_oDb->_sFieldDescription]), 0, 255));
        $this->_oTemplate->addPageKeywords ($aNightlifeEntry[$this->_oDb->_sFieldTags]);

        $this->_oTemplate->addCss ('view.css');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('entry_view.css');
        $this->_oTemplate->addCss ('unit_fan.css');

		$sPageTitle = $aNightlifeEntry[$this->_oDb->_sFieldTitle] .' | '. $aDataEntry[$this->_oDb->_sFieldTitle];

        $this->_oTemplate->pageCode($sPageTitle, false, false);

        bx_import ('BxDolViews');
        new BxDolViews($this->_oDb->_sNightlifePrefix, $aDataEntry[$this->_oDb->_sFieldId]);
    }


    function actionNightlifeEdit ($iEntryId, $sTitle) { 

        $iEntryId = (int)$iEntryId;

		$aNightlifeEntry = $this->_oDb->getNightlifeEntryById($iEntryId);
		$iNightlifeId = (int)$aNightlifeEntry['location_id'];
  
        if (!($aDataEntry = $this->_oDb->getEntryById($iNightlifeId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }
  
        if (!$this->isAllowedSubEdit($aDataEntry, $aNightlifeEntry)) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }

        $this->_oTemplate->pageStart();
		
		$this->_oTemplate->addInjection('injection_body', 'text',  'onload="fillCombo();"');

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);

        bx_import ('NightlifeFormEdit', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'NightlifeFormEdit';
        $oForm = new $sClass ($this, $aNightlifeEntry[$this->_oDb->_sFieldAuthorId], $iNightlifeId,  $iEntryId, $aNightlifeEntry);
  
        $oForm->initChecker($aNightlifeEntry);

        if ($oForm->isSubmittedAndValid ()) {
 
            $this->_oDb->_sTableMain = 'nightlife_main';
			$this->_oDb->_sTableMediaPrefix = $this->_oDb->_sTableNightlifeMediaPrefix;
 
			$aValsAdd = array();
 			if (isset($_FILES['photo']['tmp_name']) && $_FILES['photo']['tmp_name'])
				$aValsAdd['photo'] = $oForm->uploadPhoto($_FILES['photo']['tmp_name']);
	 
            if ($oForm->update ($iEntryId, $aValsAdd)) {
   
				$aDeals2Keep = array(); 
				if( is_array($_POST['prev_deal']) && count($_POST['prev_deal'])){
					foreach ($_POST['prev_deal'] as $iDealId){
						$aDeals2Keep[$iDealId] = $iDealId;
					}
				}

				$aDealIds = $this->_oDb->getDealIds($iEntryId, 'nightlife');
			
				$aDeletedDeal = array_diff ($aDealIds, $aDeals2Keep);

				if ($aDeletedDeal) {
					foreach ($aDeletedDeal as $iDealId) {
						$this->_oDb->removeDeal($iEntryId, $iDealId, 'nightlife');
					}
				}
				 
				$this->_oDb->addDeal($iEntryId, 'nightlife');
				  
				$oForm->processMedia($iEntryId, $this->_iProfileId);
  
                $this->isAllowedEdit($aDataEntry, true); // perform action

                $this->onEventSubProfileChanged ('nightlife', $iEntryId, $sStatus);
                header ('Location:' . BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'nightlife/view/' . $aNightlifeEntry[$this->_oDb->_sFieldUri]);
                exit;

            } else {

                echo MsgBox(_t('_Error Occured'));
                
            }            

        } else {

            echo $oForm->getCode ();

        }

        $this->_oTemplate->addJs ('main.js');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('forms_extra.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry['title']));  
    }

    function actionNightlifeDelete ($iNightlifeId, $sMsgSuccess) {

		$aNightlifeEntry = $this->_oDb->getNightlifeEntryById($iNightlifeId);
		$iEntryId = (int)$aNightlifeEntry['location_id'];
  
        if (!($aDataEntry = $this->_oDb->getEntryByIdAndOwner($iEntryId, $this->_iProfileId, $this->isAdmin()))) {
            echo MsgBox(_t('_sys_request_page_not_found_cpt')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }

        if (!$this->isAllowedSubDelete($aDataEntry, $aNightlifeEntry) || 0 != strcasecmp($_SERVER['REQUEST_METHOD'], 'POST')) {
            echo MsgBox(_t('_Access denied')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }

        if ($this->_oDb->deleteNightlifeByIdAndOwner($iNightlifeId, $iEntryId, $this->_iProfileId, $this->isAdmin())) {
            $this->isAllowedDelete($aDataEntry, true); // perform action
            $this->onEventNightlifeDeleted ($iEntryId, $aDataEntry);            
            $sRedirect = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri];
  
            $sJQueryJS = genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div', $sRedirect);
            echo MsgBox(_t($sMsgSuccess)) . $sJQueryJS;
            exit;
        }

        echo MsgBox(_t('_Error Occured')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
        exit;
    }
 
    function actionNightlifeAdd ($iNightlifeId, $sTitle) {
  
        if (!$this->isAllowedAdd()) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }
 
		if (!($aDataEntry = $this->_oDb->getEntryById($iNightlifeId))) {
			$this->_oTemplate->displayPageNotFound ();
			return;
		}	

        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);

		$this->_oTemplate->addInjection('injection_body', 'text',  'onload="fillCombo();"');

        $this->_addNightlifeForm($iNightlifeId);

        $this->_oTemplate->addJs ('main.js');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('forms_extra.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry['title']));  
    }
 
    function _addNightlifeForm ($iNightlifeId) { 
 
        bx_import ('NightlifeFormAdd', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'NightlifeFormAdd';
        $oForm = new $sClass ($this, $this->_iProfileId, $iNightlifeId);
        $oForm->initChecker();

        if ($oForm->isSubmittedAndValid ()) {
 
			$sStatus = 'approved';

            $this->_oDb->_sTableMain = 'nightlife_main';
			$this->_oDb->_sTableMediaPrefix = $this->_oDb->_sTableNightlifeMediaPrefix;
 
            $aValsAdd = array (
                $this->_oDb->_sFieldCreated => time(),
                $this->_oDb->_sFieldUri => $oForm->generateUri(),
                $this->_oDb->_sFieldStatus => $sStatus,
				$this->_oDb->_sFieldAuthorId => $this->_iProfileId 
            ); 
			
 			if (isset($_FILES['photo']['tmp_name']) && $_FILES['photo']['tmp_name'])
				$aValsAdd['photo'] = $oForm->uploadPhoto($_FILES['photo']['tmp_name']);
	   
            $iEntryId = $oForm->insert ($aValsAdd);
 
            if ($iEntryId) {

                $this->isAllowedAdd(true); // perform action                 
   
				$this->_oDb->addDeal($iEntryId, 'nightlife');

				$oForm->processMedia($iEntryId, $this->_iProfileId); 
	  
                $aDataEntry = $this->_oDb->getNightlifeEntryById($iEntryId);
                $this->onEventSubProfileCreate('nightlife', $iEntryId, $sStatus, $aDataEntry);
   
				$sRedirectUrl = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'nightlife/view/' . $aDataEntry[$this->_oDb->_sFieldUri];
			  
                header ('Location:' . $sRedirectUrl);
                exit;

            } else {

                MsgBox(_t('_Error Occured'));
            }
                         
        } else { 
            echo $oForm->getCode (); 
        }
    }
  
    function reparseSubProfileTags ($sType, $iEntryId) {
        $iEntryId = (int)$iEntryId;
        bx_import('BxDolTags');
        $o = new BxDolTags ();
 
		switch($sType){
			case 'nightlife': 
				$o->reparseObjTags($this->_sNightlifePrefix, $iEntryId);
			break;
			case 'shop': 
				$o->reparseObjTags($this->_sShopPrefix, $iEntryId);
			break;
			case 'school': 
				$o->reparseObjTags($this->_sSchoolPrefix, $iEntryId);
			break;
			case 'service': 
				$o->reparseObjTags($this->_sServicePrefix, $iEntryId);
			break;
			case 'hotel': 
				$o->reparseObjTags($this->_sHotelPrefix, $iEntryId);
			break;
			case 'event': 
				$o->reparseObjTags($this->_sEventPrefix, $iEntryId);
			break;
			case 'transport': 
				$o->reparseObjTags($this->_sTransportPrefix, $iEntryId);
			break;
			case 'food': 
				$o->reparseObjTags($this->_sFoodPrefix, $iEntryId);
			break;
		} 
    }

    function reparseSubProfileCategories ($sType, $iEntryId) {
        $iEntryId = (int)$iEntryId;
        bx_import('BxDolCategories');
        $o = new BxDolCategories ();
 
		switch($sType){
			case 'nightlife': 
				$o->reparseObjTags($this->_sNightlifePrefix, $iEntryId);
			break;
			case 'shop': 
				$o->reparseObjTags($this->_sShopPrefix, $iEntryId);
			break;
			case 'school': 
				$o->reparseObjTags($this->_sSchoolPrefix, $iEntryId);
			break;
			case 'service': 
				$o->reparseObjTags($this->_sServicePrefix, $iEntryId);
			break;
			case 'hotel': 
				$o->reparseObjTags($this->_sHotelPrefix, $iEntryId);
			break;
			case 'event': 
				$o->reparseObjTags($this->_sEventPrefix, $iEntryId);
			break;
			case 'transport': 
				$o->reparseObjTags($this->_sTransportPrefix, $iEntryId);
			break;
			case 'food': 
				$o->reparseObjTags($this->_sFoodPrefix, $iEntryId);
			break;
		} 
	}
 
    function onEventSubProfileCreate ($sType, $iEntryId, $sStatus, $aDataEntry = array()) {
        
		$this->serviceUpdateSubProfileLocation ($sType, $iEntryId);
		
		if ('approved' == $sStatus) {

			$this->reparseSubProfileTags ($sType, $iEntryId);
			$this->reparseSubProfileCategories ($sType, $iEntryId); 
        }
 
		//$oAlert = new BxDolAlerts($this->_sPrefix, 'add', $iEntryId, $this->_iProfileId, array('Status' => $sStatus));
		//$oAlert->alert();
    }


    function onEventSubProfileChanged($sType, $iEntryId, $sStatus) {
       
		$this->serviceUpdateSubProfileLocation ($sType, $iEntryId);

		$this->reparseSubProfileTags ($sType, $iEntryId);
		$this->reparseSubProfileCategories ($sType, $iEntryId); 
   
		//$oAlert = new BxDolAlerts($this->_sPrefix, 'change', $iEntryId, $this->_iProfileId, array('Status' => $sStatus));
		//$oAlert->alert();
    }
 

    function onEventNightlifeDeleted ($iEntryId, $aDataEntry = array()) {

        // delete associated tags and categories 
		$this->reparseSubProfileTags ('nightlife', $iEntryId);
		$this->reparseSubProfileCategories ('nightlife', $iEntryId); 

        // delete votings
        bx_import('NightlifeVoting', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'NightlifeVoting';
        $oVoting = new $sClass ($this->_oDb->_sNightlifePrefix, 0, 0);
        $oVoting->deleteVotings ($iEntryId);

        // delete comments 
        bx_import('NightlifeCmts', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'NightlifeCmts';
        $oCmts = new $sClass ($this->_oDb->_sNightlifePrefix, $iEntryId);
        $oCmts->onObjectDelete ();

        // delete views
        bx_import ('BxDolViews');
        $oViews = new BxDolViews($this->_oDb->_sNightlifePrefix, $iEntryId, false);
        $oViews->onObjectDelete();

 
        // arise alert
		//$oAlert = new BxDolAlerts($this->_sPrefix, 'delete', $iEntryId, $this->_iProfileId);
		//$oAlert->alert();
    }        


    /*******[END - Nightlife Functions] ******************************/


	/******[BEGIN] Hotel functions **************************/ 
    function actionHotel ($sAction, $sIdUri) {
		switch($sAction){
			case 'add': 
				$this->actionHotelAdd ($sIdUri, '_modzzz_location_page_title_hotel_add');
			break;
			case 'edit':
				$this->actionHotelEdit ($sIdUri, '_modzzz_location_page_title_hotel_edit');
			break;
			case 'delete':
				$this->actionHotelDelete ($sIdUri, _t('_modzzz_location_msg_location_was_hotel_deleted'));
			break;
			case 'view':
				$this->actionHotelView ($sIdUri, _t('_modzzz_location_msg_pending_hotel_approval')); 
			break; 
			case 'browse':
				return $this->actionHotelBrowse ($sIdUri, '_modzzz_location_page_title_hotel_browse'); 
			break;  
		}
	}
    
    function actionHotelBrowse ($sUri, $sTitle) {
       
        if (!($aDataEntry = $this->_oDb->getEntryByUri($sUri))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }		
		
		$this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);

        bx_import ('HotelPageBrowse', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'HotelPageBrowse';
        $oPage = new $sClass ($this, $sUri);
        echo $oPage->getCode();
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('unit.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry['title']), false, false);  
    }
 
    function actionHotelView ($sUri, $sMsgPendingApproval) {

		$aHotelEntry = $this->_oDb->getHotelEntryByUri($sUri);
		$iEntryId = (int)$aHotelEntry['location_id'];
 
        if (!($aDataEntry = $this->_oDb->getEntryById($iEntryId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }
 
        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aHotelEntry[$this->_oDb->_sFieldTitle] .' - '. $aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);
 
        bx_import ('HotelPageView', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'HotelPageView';
        $oPage = new $sClass ($this, $aHotelEntry);

        if ($aDataEntry[$this->_oDb->_sFieldStatus] == 'pending') {
            $aVars = array ('msg' => $sMsgPendingApproval); // this product is pending approval, please wait until it will be activated
            echo $this->_oTemplate->parseHtmlByName ('pending_approval_plank', $aVars);
        }

        echo $oPage->getCode();

        bx_import('HotelCmts', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'HotelCmts';
        $oCmts = new $sClass ($this->_sPrefix, 0);

        $this->_oTemplate->setPageDescription (substr(strip_tags($aHotelEntry[$this->_oDb->_sFieldDescription]), 0, 255));
        $this->_oTemplate->addPageKeywords ($aHotelEntry[$this->_oDb->_sFieldTags]);

        $this->_oTemplate->addCss ('view.css');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('entry_view.css');
        $this->_oTemplate->addCss ('unit_fan.css');

		$sPageTitle = $aHotelEntry[$this->_oDb->_sFieldTitle] .' | '. $aDataEntry[$this->_oDb->_sFieldTitle];

        $this->_oTemplate->pageCode($sPageTitle, false, false);

        bx_import ('BxDolViews');
        new BxDolViews($this->_oDb->_sHotelPrefix, $aDataEntry[$this->_oDb->_sFieldId]);
    }


    function actionHotelEdit ($iEntryId, $sTitle) { 

        $iEntryId = (int)$iEntryId;

		$aHotelEntry = $this->_oDb->getHotelEntryById($iEntryId);
		$iHotelId = (int)$aHotelEntry['location_id'];
  
        if (!($aDataEntry = $this->_oDb->getEntryById($iHotelId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }
  
        if (!$this->isAllowedSubEdit($aDataEntry, $aHotelEntry)) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }

        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);

        bx_import ('HotelFormEdit', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'HotelFormEdit';
        $oForm = new $sClass ($this, $aHotelEntry[$this->_oDb->_sFieldAuthorId], $iHotelId,  $iEntryId, $aHotelEntry);
  
        $oForm->initChecker($aHotelEntry);

        if ($oForm->isSubmittedAndValid ()) {
 
            $this->_oDb->_sTableMain = 'hotel_main';
			$this->_oDb->_sTableMediaPrefix = $this->_oDb->_sTableHotelMediaPrefix;
 
            $aValsAdd = array (); 
			
			if ($oForm->update ($iEntryId, $aValsAdd)) {
  
				$oForm->processMedia($iEntryId, $this->_iProfileId);
  
                $this->isAllowedEdit($aDataEntry, true); // perform action

                $this->onEventSubProfileChanged ('hotel', $iEntryId, $sStatus);
                header ('Location:' . BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'hotel/view/' . $aHotelEntry[$this->_oDb->_sFieldUri]);
                exit;

            } else {

                echo MsgBox(_t('_Error Occured'));
                
            }            

        } else {

            echo $oForm->getCode ();

        }

        $this->_oTemplate->addJs ('main.js');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('forms_extra.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry['title']));  
    }

    function actionHotelDelete ($iHotelId, $sMsgSuccess) {

		$aHotelEntry = $this->_oDb->getHotelEntryById($iHotelId);
		$iEntryId = (int)$aHotelEntry['location_id'];
  
        if (!($aDataEntry = $this->_oDb->getEntryByIdAndOwner($iEntryId, $this->_iProfileId, $this->isAdmin()))) {
            echo MsgBox(_t('_sys_request_page_not_found_cpt')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }

        if (!$this->isAllowedSubDelete($aDataEntry, $aHotelEntry) || 0 != strcasecmp($_SERVER['REQUEST_METHOD'], 'POST')) {
            echo MsgBox(_t('_Access denied')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }

        if ($this->_oDb->deleteHotelByIdAndOwner($iHotelId, $iEntryId, $this->_iProfileId, $this->isAdmin())) {
            $this->isAllowedDelete($aDataEntry, true); // perform action
            $this->onEventHotelDeleted ($iEntryId, $aDataEntry);            
            $sRedirect = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri];
  
            $sJQueryJS = genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div', $sRedirect);
            echo MsgBox(_t($sMsgSuccess)) . $sJQueryJS;
            exit;
        }

        echo MsgBox(_t('_Error Occured')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
        exit;
    }
 
    function actionHotelAdd ($iHotelId, $sTitle) {
  
        if (!$this->isAllowedAdd()) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }
 
		if (!($aDataEntry = $this->_oDb->getEntryById($iHotelId))) {
			$this->_oTemplate->displayPageNotFound ();
			return;
		}	

        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);


        $this->_addHotelForm($iHotelId);

        $this->_oTemplate->addJs ('main.js');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('forms_extra.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry['title']));  
    }
 
    function _addHotelForm ($iHotelId) { 
 
        bx_import ('HotelFormAdd', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'HotelFormAdd';
        $oForm = new $sClass ($this, $this->_iProfileId, $iHotelId);
        $oForm->initChecker();

        if ($oForm->isSubmittedAndValid ()) {
 
			$sStatus = 'approved';

            $this->_oDb->_sTableMain = 'hotel_main';
			$this->_oDb->_sTableMediaPrefix = $this->_oDb->_sTableHotelMediaPrefix;
 
            $aValsAdd = array (
                $this->_oDb->_sFieldCreated => time(),
                $this->_oDb->_sFieldUri => $oForm->generateUri(),
                $this->_oDb->_sFieldStatus => $sStatus,
				$this->_oDb->_sFieldAuthorId => $this->_iProfileId,   
            );                        
 
            $iEntryId = $oForm->insert ($aValsAdd);
 
            if ($iEntryId) {

                $this->isAllowedAdd(true); // perform action                 
 
				$oForm->processMedia($iEntryId, $this->_iProfileId); 
	  
                $aDataEntry = $this->_oDb->getHotelEntryById($iEntryId);
                $this->onEventSubProfileCreate('hotel', $iEntryId, $sStatus, $aDataEntry);
   
				$sRedirectUrl = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'hotel/view/' . $aDataEntry[$this->_oDb->_sFieldUri];
			  
                header ('Location:' . $sRedirectUrl);
                exit;

            } else {

                MsgBox(_t('_Error Occured'));
            }
                         
        } else { 
            echo $oForm->getCode (); 
        }
    }
 
    function onEventHotelDeleted ($iEntryId, $aDataEntry = array()) {

        // delete associated tags and categories 
		$this->reparseSubProfileTags ('hotel', $iEntryId);
		$this->reparseSubProfileCategories ('hotel', $iEntryId); 

        // delete votings
        bx_import('HotelVoting', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'HotelVoting';
        $oVoting = new $sClass ($this->_oDb->_sHotelPrefix, 0, 0);
        $oVoting->deleteVotings ($iEntryId);

        // delete comments 
        bx_import('HotelCmts', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'HotelCmts';
        $oCmts = new $sClass ($this->_oDb->_sHotelPrefix, $iEntryId);
        $oCmts->onObjectDelete ();

        // delete views
        bx_import ('BxDolViews');
        $oViews = new BxDolViews($this->_oDb->_sHotelPrefix, $iEntryId, false);
        $oViews->onObjectDelete();

 
        // arise alert
		//$oAlert = new BxDolAlerts($this->_sPrefix, 'delete', $iEntryId, $this->_iProfileId);
		//$oAlert->alert();
    }        


    /*******[END - Hotel Functions] ******************************/


	/******[BEGIN] Food functions **************************/ 
    function actionFood ($sAction, $sIdUri) {
		switch($sAction){
			case 'add': 
				$this->actionFoodAdd ($sIdUri, '_modzzz_location_page_title_food_add');
			break;
			case 'edit':
				$this->actionFoodEdit ($sIdUri, '_modzzz_location_page_title_food_edit');
			break;
			case 'delete':
				$this->actionFoodDelete ($sIdUri, _t('_modzzz_location_msg_location_was_food_deleted'));
			break;
			case 'view':
				$this->actionFoodView ($sIdUri, _t('_modzzz_location_msg_pending_food_approval')); 
			break; 
			case 'browse':
				return $this->actionFoodBrowse ($sIdUri, '_modzzz_location_page_title_food_browse'); 
			break;  
		}
	}
    
    function actionFoodBrowse ($sUri, $sTitle) {
       
        if (!($aDataEntry = $this->_oDb->getEntryByUri($sUri))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }		
		
		$this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);

        bx_import ('FoodPageBrowse', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'FoodPageBrowse';
        $oPage = new $sClass ($this, $sUri);
        echo $oPage->getCode();
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('unit.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry['title']), false, false);  
    }
 
    function actionFoodView ($sUri, $sMsgPendingApproval) {

		$aFoodEntry = $this->_oDb->getFoodEntryByUri($sUri);
		$iEntryId = (int)$aFoodEntry['location_id'];
 
        if (!($aDataEntry = $this->_oDb->getEntryById($iEntryId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }
 
        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aFoodEntry[$this->_oDb->_sFieldTitle] .' - '. $aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);
 
        bx_import ('FoodPageView', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'FoodPageView';
        $oPage = new $sClass ($this, $aFoodEntry);

        if ($aDataEntry[$this->_oDb->_sFieldStatus] == 'pending') {
            $aVars = array ('msg' => $sMsgPendingApproval); // this product is pending approval, please wait until it will be activated
            echo $this->_oTemplate->parseHtmlByName ('pending_approval_plank', $aVars);
        }

        echo $oPage->getCode();

        bx_import('FoodCmts', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'FoodCmts';
        $oCmts = new $sClass ($this->_sPrefix, 0);

        $this->_oTemplate->setPageDescription (substr(strip_tags($aFoodEntry[$this->_oDb->_sFieldDescription]), 0, 255));
        $this->_oTemplate->addPageKeywords ($aFoodEntry[$this->_oDb->_sFieldTags]);

        $this->_oTemplate->addCss ('view.css');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('entry_view.css');
        $this->_oTemplate->addCss ('unit_fan.css');

		$sPageTitle = $aFoodEntry[$this->_oDb->_sFieldTitle] .' | '. $aDataEntry[$this->_oDb->_sFieldTitle];

        $this->_oTemplate->pageCode($sPageTitle, false, false);

        bx_import ('BxDolViews');
        new BxDolViews($this->_oDb->_sFoodPrefix, $aDataEntry[$this->_oDb->_sFieldId]);
    }


    function actionFoodEdit ($iEntryId, $sTitle) { 

        $iEntryId = (int)$iEntryId;

		$aFoodEntry = $this->_oDb->getFoodEntryById($iEntryId);
		$iFoodId = (int)$aFoodEntry['location_id'];
  
        if (!($aDataEntry = $this->_oDb->getEntryById($iFoodId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }
  
        if (!$this->isAllowedSubEdit($aDataEntry, $aFoodEntry)) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }

        $this->_oTemplate->pageStart();

		$this->_oTemplate->addInjection('injection_body', 'text',  'onload="fillCombo();"');

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);

        bx_import ('FoodFormEdit', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'FoodFormEdit';
        $oForm = new $sClass ($this, $aFoodEntry[$this->_oDb->_sFieldAuthorId], $iFoodId,  $iEntryId, $aFoodEntry);
  
        $oForm->initChecker($aFoodEntry);

        if ($oForm->isSubmittedAndValid ()) {
 
            $this->_oDb->_sTableMain = 'food_main';
			$this->_oDb->_sTableMediaPrefix = $this->_oDb->_sTableFoodMediaPrefix;
 
            if ($oForm->update ($iEntryId, $aValsAdd)) {
  
				$aDeals2Keep = array(); 
				if( is_array($_POST['prev_deal']) &&count($_POST['prev_deal'])){
					foreach ($_POST['prev_deal'] as $iDealId){
						$aDeals2Keep[$iDealId] = $iDealId;
					}
				}

				$aDealIds = $this->_oDb->getDealIds($iEntryId, 'food');
			
				$aDeletedDeal = array_diff ($aDealIds, $aDeals2Keep);

				if ($aDeletedDeal) {
					foreach ($aDeletedDeal as $iDealId) {
						$this->_oDb->removeDeal($iEntryId, $iDealId, 'food');
					}
				}
				 
				$this->_oDb->addDeal($iEntryId, 'food');
 
				$oForm->processMedia($iEntryId, $this->_iProfileId);
  
                $this->isAllowedEdit($aDataEntry, true); // perform action

                $this->onEventSubProfileChanged ('food', $iEntryId, $sStatus);
                header ('Location:' . BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'food/view/' . $aFoodEntry[$this->_oDb->_sFieldUri]);
                exit;

            } else {

                echo MsgBox(_t('_Error Occured'));
                
            }            

        } else {

            echo $oForm->getCode ();

        }

        $this->_oTemplate->addJs ('main.js');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('forms_extra.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry['title']));  
    }

    function actionFoodDelete ($iFoodId, $sMsgSuccess) {

		$aFoodEntry = $this->_oDb->getFoodEntryById($iFoodId);
		$iEntryId = (int)$aFoodEntry['location_id'];
  
        if (!($aDataEntry = $this->_oDb->getEntryByIdAndOwner($iEntryId, $this->_iProfileId, $this->isAdmin()))) {
            echo MsgBox(_t('_sys_request_page_not_found_cpt')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }

        if (!$this->isAllowedSubDelete($aDataEntry, $aFoodEntry) || 0 != strcasecmp($_SERVER['REQUEST_METHOD'], 'POST')) {
            echo MsgBox(_t('_Access denied')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }

        if ($this->_oDb->deleteFoodByIdAndOwner($iFoodId, $iEntryId, $this->_iProfileId, $this->isAdmin())) {
            $this->isAllowedDelete($aDataEntry, true); // perform action
            $this->onEventFoodDeleted ($iEntryId, $aDataEntry);            
            $sRedirect = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri];
  
            $sJQueryJS = genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div', $sRedirect);
            echo MsgBox(_t($sMsgSuccess)) . $sJQueryJS;
            exit;
        }

        echo MsgBox(_t('_Error Occured')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
        exit;
    }
 
    function actionFoodAdd ($iFoodId, $sTitle) {
  
        if (!$this->isAllowedAdd()) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }
 
		if (!($aDataEntry = $this->_oDb->getEntryById($iFoodId))) {
			$this->_oTemplate->displayPageNotFound ();
			return;
		}	

        $this->_oTemplate->pageStart();

		$this->_oTemplate->addInjection('injection_body', 'text',  'onload="fillCombo();"');

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);


        $this->_addFoodForm($iFoodId);

        $this->_oTemplate->addJs ('main.js');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('forms_extra.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry['title']));  
    }
 
    function _addFoodForm ($iFoodId) { 
 
        bx_import ('FoodFormAdd', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'FoodFormAdd';
        $oForm = new $sClass ($this, $this->_iProfileId, $iFoodId);
        $oForm->initChecker();

        if ($oForm->isSubmittedAndValid ()) {
 
			$sStatus = 'approved';

            $this->_oDb->_sTableMain = 'food_main';
			$this->_oDb->_sTableMediaPrefix = $this->_oDb->_sTableFoodMediaPrefix;
 
            $aValsAdd = array (
                $this->_oDb->_sFieldCreated => time(),
                $this->_oDb->_sFieldUri => $oForm->generateUri(),
                $this->_oDb->_sFieldStatus => $sStatus,
				$this->_oDb->_sFieldAuthorId => $this->_iProfileId 
            );                        
 
            $iEntryId = $oForm->insert ($aValsAdd);
 
            if ($iEntryId) {

                $this->isAllowedAdd(true); // perform action                 
 
 				$this->_oDb->addDeal($iEntryId, 'food');

				$oForm->processMedia($iEntryId, $this->_iProfileId); 
	  
                $aDataEntry = $this->_oDb->getFoodEntryById($iEntryId);
                $this->onEventSubProfileCreate('food', $iEntryId, $sStatus, $aDataEntry);
   
				$sRedirectUrl = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'food/view/' . $aDataEntry[$this->_oDb->_sFieldUri];
			  
                header ('Location:' . $sRedirectUrl);
                exit;

            } else {

                MsgBox(_t('_Error Occured'));
            }
                         
        } else { 
            echo $oForm->getCode (); 
        }
    }
 
    function onEventFoodDeleted ($iEntryId, $aDataEntry = array()) {

        // delete associated tags and categories 
		$this->reparseSubProfileTags ('food', $iEntryId);
		$this->reparseSubProfileCategories ('food', $iEntryId); 

        // delete votings
        bx_import('FoodVoting', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'FoodVoting';
        $oVoting = new $sClass ($this->_oDb->_sFoodPrefix, 0, 0);
        $oVoting->deleteVotings ($iEntryId);

        // delete comments 
        bx_import('FoodCmts', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'FoodCmts';
        $oCmts = new $sClass ($this->_oDb->_sFoodPrefix, $iEntryId);
        $oCmts->onObjectDelete ();

        // delete views
        bx_import ('BxDolViews');
        $oViews = new BxDolViews($this->_oDb->_sFoodPrefix, $iEntryId, false);
        $oViews->onObjectDelete();

 
        // arise alert
		//$oAlert = new BxDolAlerts($this->_sPrefix, 'delete', $iEntryId, $this->_iProfileId);
		//$oAlert->alert();
    }        


    /*******[END - Food Functions] ******************************/


	/******[BEGIN] School functions **************************/ 
    function actionSchool ($sAction, $sIdUri) {
		switch($sAction){
			case 'add': 
				$this->actionSchoolAdd ($sIdUri, '_modzzz_location_page_title_school_add');
			break;
			case 'edit':
				$this->actionSchoolEdit ($sIdUri, '_modzzz_location_page_title_school_edit');
			break;
			case 'delete':
				$this->actionSchoolDelete ($sIdUri, _t('_modzzz_location_msg_location_was_school_deleted'));
			break;
			case 'view':
				$this->actionSchoolView ($sIdUri, _t('_modzzz_location_msg_pending_school_approval')); 
			break; 
			case 'browse': 
				return $this->actionSchoolBrowse ($sIdUri, '_modzzz_location_page_title_school_browse'); 
			break;  
		}
	}
    
    function actionSchoolBrowse ($sUri, $sTitle) {
       
        if (!($aDataEntry = $this->_oDb->getEntryByUri($sUri))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }		
		
		$this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);
 
        bx_import ('SchoolPageBrowse', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'SchoolPageBrowse';
        $oPage = new $sClass ($this, $sUri);
        echo $oPage->getCode();
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('unit.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry['title']), false, false);  
    }
 
    function actionSchoolView ($sUri, $sMsgPendingApproval) {

		$aSchoolEntry = $this->_oDb->getSchoolEntryByUri($sUri);
		$iEntryId = (int)$aSchoolEntry['location_id'];
 
        if (!($aDataEntry = $this->_oDb->getEntryById($iEntryId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }
 
        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aSchoolEntry[$this->_oDb->_sFieldTitle] .' - '. $aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);
 
        bx_import ('SchoolPageView', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'SchoolPageView';
        $oPage = new $sClass ($this, $aSchoolEntry);

        if ($aDataEntry[$this->_oDb->_sFieldStatus] == 'pending') {
            $aVars = array ('msg' => $sMsgPendingApproval); // this product is pending approval, please wait until it will be activated
            echo $this->_oTemplate->parseHtmlByName ('pending_approval_plank', $aVars);
        }

        echo $oPage->getCode();

        bx_import('SchoolCmts', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'SchoolCmts';
        $oCmts = new $sClass ($this->_sPrefix, 0);

        $this->_oTemplate->setPageDescription (substr(strip_tags($aSchoolEntry[$this->_oDb->_sFieldDescription]), 0, 255));
        $this->_oTemplate->addPageKeywords ($aSchoolEntry[$this->_oDb->_sFieldTags]);

        $this->_oTemplate->addCss ('view.css');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('entry_view.css');
        $this->_oTemplate->addCss ('unit_fan.css');

		$sPageTitle = $aSchoolEntry[$this->_oDb->_sFieldTitle] .' | '. $aDataEntry[$this->_oDb->_sFieldTitle];
 
        $this->_oTemplate->pageCode($sPageTitle, false, false);

        bx_import ('BxDolViews');
        new BxDolViews($this->_oDb->_sSchoolPrefix, $aDataEntry[$this->_oDb->_sFieldId]);
    }


    function actionSchoolEdit ($iEntryId, $sTitle) { 

        $iEntryId = (int)$iEntryId;

		$aSchoolEntry = $this->_oDb->getSchoolEntryById($iEntryId);
		$iSchoolId = (int)$aSchoolEntry['location_id'];
  
        if (!($aDataEntry = $this->_oDb->getEntryById($iSchoolId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }
  
        if (!$this->isAllowedSubEdit($aDataEntry, $aSchoolEntry)) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }

        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);

        bx_import ('SchoolFormEdit', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'SchoolFormEdit';
        $oForm = new $sClass ($this, $aSchoolEntry[$this->_oDb->_sFieldAuthorId], $iSchoolId,  $iEntryId, $aSchoolEntry);
  
        $oForm->initChecker($aSchoolEntry);

        if ($oForm->isSubmittedAndValid ()) {
 
            $this->_oDb->_sTableMain = 'school_main';
			$this->_oDb->_sTableMediaPrefix = $this->_oDb->_sTableSchoolMediaPrefix;


            if ($oForm->update ($iEntryId, $aValsAdd)) {
  
				$oForm->processMedia($iEntryId, $this->_iProfileId);
  
                $this->isAllowedEdit($aDataEntry, true); // perform action

                $this->onEventSubProfileChanged ('school', $iEntryId, $sStatus);
                header ('Location:' . BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'school/view/' . $aSchoolEntry[$this->_oDb->_sFieldUri]);
                exit;

            } else {

                echo MsgBox(_t('_Error Occured'));
                
            }            

        } else {

            echo $oForm->getCode ();

        }

        $this->_oTemplate->addJs ('main.js');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('forms_extra.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry['title']));  
    }

    function actionSchoolDelete ($iSchoolId, $sMsgSuccess) {

		$aSchoolEntry = $this->_oDb->getSchoolEntryById($iSchoolId);
		$iEntryId = (int)$aSchoolEntry['location_id'];
  
        if (!($aDataEntry = $this->_oDb->getEntryByIdAndOwner($iEntryId, $this->_iProfileId, $this->isAdmin()))) {
            echo MsgBox(_t('_sys_request_page_not_found_cpt')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }

        if (!$this->isAllowedSubDelete($aDataEntry, $aSchoolEntry) || 0 != strcasecmp($_SERVER['REQUEST_METHOD'], 'POST')) {
            echo MsgBox(_t('_Access denied')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }

        if ($this->_oDb->deleteSchoolByIdAndOwner($iSchoolId, $iEntryId, $this->_iProfileId, $this->isAdmin())) {
            $this->isAllowedDelete($aDataEntry, true); // perform action
            $this->onEventSchoolDeleted ($iEntryId, $aDataEntry);            
            $sRedirect = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri];
  
            $sJQueryJS = genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div', $sRedirect);
            echo MsgBox(_t($sMsgSuccess)) . $sJQueryJS;
            exit;
        }

        echo MsgBox(_t('_Error Occured')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
        exit;
    }
 
    function actionSchoolAdd ($iSchoolId, $sTitle) {
  
        if (!$this->isAllowedAdd()) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }


		if (!($aDataEntry = $this->_oDb->getEntryById($iSchoolId))) {
			$this->_oTemplate->displayPageNotFound ();
			return;
		}	

        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);


        $this->_addSchoolForm($iSchoolId);

        $this->_oTemplate->addJs ('main.js');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('forms_extra.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry['title']));  
    }
 
    function _addSchoolForm ($iSchoolId) { 
 
        bx_import ('SchoolFormAdd', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'SchoolFormAdd';
        $oForm = new $sClass ($this, $this->_iProfileId, $iSchoolId);
        $oForm->initChecker();

        if ($oForm->isSubmittedAndValid ()) {
 
			$sStatus = 'approved';

            $this->_oDb->_sTableMain = 'school_main';
			$this->_oDb->_sTableMediaPrefix = $this->_oDb->_sTableSchoolMediaPrefix;
 
            $aValsAdd = array (
                $this->_oDb->_sFieldCreated => time(),
                $this->_oDb->_sFieldUri => $oForm->generateUri(),
                $this->_oDb->_sFieldStatus => $sStatus,
				$this->_oDb->_sFieldAuthorId => $this->_iProfileId 
            );                        
 
            $iEntryId = $oForm->insert ($aValsAdd);
 
            if ($iEntryId) {

                $this->isAllowedAdd(true); // perform action                 
 
				$oForm->processMedia($iEntryId, $this->_iProfileId); 
	  
                $aDataEntry = $this->_oDb->getSchoolEntryById($iEntryId);
                $this->onEventSubProfileCreate('school', $iEntryId, $sStatus, $aDataEntry);
   
				$sRedirectUrl = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'school/view/' . $aDataEntry[$this->_oDb->_sFieldUri];
			  
                header ('Location:' . $sRedirectUrl);
                exit;

            } else {

                MsgBox(_t('_Error Occured'));
            }
                         
        } else { 
            echo $oForm->getCode (); 
        }
    }
 
    function onEventSchoolDeleted ($iEntryId, $aDataEntry = array()) {

        // delete associated tags and categories 
		$this->reparseSubProfileTags ('school', $iEntryId);
		$this->reparseSubProfileCategories ('school', $iEntryId); 

        // delete votings
        bx_import('SchoolVoting', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'SchoolVoting';
        $oVoting = new $sClass ($this->_oDb->_sSchoolPrefix, 0, 0);
        $oVoting->deleteVotings ($iEntryId);

        // delete comments 
        bx_import('SchoolCmts', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'SchoolCmts';
        $oCmts = new $sClass ($this->_oDb->_sSchoolPrefix, $iEntryId);
        $oCmts->onObjectDelete ();

        // delete views
        bx_import ('BxDolViews');
        $oViews = new BxDolViews($this->_oDb->_sSchoolPrefix, $iEntryId, false);
        $oViews->onObjectDelete();

 
        // arise alert
		//$oAlert = new BxDolAlerts($this->_sPrefix, 'delete', $iEntryId, $this->_iProfileId);
		//$oAlert->alert();
    }        
 
    /*******[END - School Functions] ******************************/


	/******[BEGIN] Service functions **************************/ 
    function actionService ($sAction, $sIdUri) {
		switch($sAction){
			case 'add': 
				$this->actionServiceAdd ($sIdUri, '_modzzz_location_page_title_service_add');
			break;
			case 'edit':
				$this->actionServiceEdit ($sIdUri, '_modzzz_location_page_title_service_edit');
			break;
			case 'delete':
				$this->actionServiceDelete ($sIdUri, _t('_modzzz_location_msg_location_was_service_deleted'));
			break;
			case 'view':
				$this->actionServiceView ($sIdUri, _t('_modzzz_location_msg_pending_service_approval')); 
			break; 
			case 'browse':
				return $this->actionServiceBrowse ($sIdUri, '_modzzz_location_page_title_service_browse'); 
			break;  
		}
	}
    
    function actionServiceBrowse ($sUri, $sTitle) {
       
        if (!($aDataEntry = $this->_oDb->getEntryByUri($sUri))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }		
		
		$this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);

        bx_import ('ServicePageBrowse', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'ServicePageBrowse';
        $oPage = new $sClass ($this, $sUri);
        echo $oPage->getCode();
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('unit.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry['title']), false, false);  
    }
 
    function actionServiceView ($sUri, $sMsgPendingApproval) {

		$aServiceEntry = $this->_oDb->getServiceEntryByUri($sUri);
		$iEntryId = (int)$aServiceEntry['location_id'];
 
        if (!($aDataEntry = $this->_oDb->getEntryById($iEntryId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }
 
        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aServiceEntry[$this->_oDb->_sFieldTitle] .' - '. $aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);
 
        bx_import ('ServicePageView', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'ServicePageView';
        $oPage = new $sClass ($this, $aServiceEntry);

        if ($aDataEntry[$this->_oDb->_sFieldStatus] == 'pending') {
            $aVars = array ('msg' => $sMsgPendingApproval); // this product is pending approval, please wait until it will be activated
            echo $this->_oTemplate->parseHtmlByName ('pending_approval_plank', $aVars);
        }

        echo $oPage->getCode();

        bx_import('ServiceCmts', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'ServiceCmts';
        $oCmts = new $sClass ($this->_sPrefix, 0);

        $this->_oTemplate->setPageDescription (substr(strip_tags($aServiceEntry[$this->_oDb->_sFieldDescription]), 0, 255));
        $this->_oTemplate->addPageKeywords ($aServiceEntry[$this->_oDb->_sFieldTags]);

        $this->_oTemplate->addCss ('view.css');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('entry_view.css');
        $this->_oTemplate->addCss ('unit_fan.css');

		$sPageTitle = $aServiceEntry[$this->_oDb->_sFieldTitle] .' | '. $aDataEntry[$this->_oDb->_sFieldTitle];

        $this->_oTemplate->pageCode($sPageTitle, false, false);

        bx_import ('BxDolViews');
        new BxDolViews($this->_oDb->_sServicePrefix, $aDataEntry[$this->_oDb->_sFieldId]);
    }


    function actionServiceEdit ($iEntryId, $sTitle) { 

        $iEntryId = (int)$iEntryId;

		$aServiceEntry = $this->_oDb->getServiceEntryById($iEntryId);
		$iServiceId = (int)$aServiceEntry['location_id'];
  
        if (!($aDataEntry = $this->_oDb->getEntryById($iServiceId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }
  
        if (!$this->isAllowedSubEdit($aDataEntry, $aServiceEntry)) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }

        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);

        bx_import ('ServiceFormEdit', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'ServiceFormEdit';
        $oForm = new $sClass ($this, $aServiceEntry[$this->_oDb->_sFieldAuthorId], $iServiceId,  $iEntryId, $aServiceEntry);
  
        $oForm->initChecker($aServiceEntry);

        if ($oForm->isSubmittedAndValid ()) {
 
            $this->_oDb->_sTableMain = 'service_main';
			$this->_oDb->_sTableMediaPrefix = $this->_oDb->_sTableServiceMediaPrefix;


            if ($oForm->update ($iEntryId, $aValsAdd)) {
  
				$oForm->processMedia($iEntryId, $this->_iProfileId);
  
                $this->isAllowedEdit($aDataEntry, true); // perform action

                $this->onEventSubProfileChanged ('service', $iEntryId, $sStatus);
                header ('Location:' . BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'service/view/' . $aServiceEntry[$this->_oDb->_sFieldUri]);
                exit;

            } else {

                echo MsgBox(_t('_Error Occured'));
                
            }            

        } else {

            echo $oForm->getCode ();

        }

        $this->_oTemplate->addJs ('main.js');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('forms_extra.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry['title']));  
    }

    function actionServiceDelete ($iServiceId, $sMsgSuccess) {

		$aServiceEntry = $this->_oDb->getServiceEntryById($iServiceId);
		$iEntryId = (int)$aServiceEntry['location_id'];
  
        if (!($aDataEntry = $this->_oDb->getEntryByIdAndOwner($iEntryId, $this->_iProfileId, $this->isAdmin()))) {
            echo MsgBox(_t('_sys_request_page_not_found_cpt')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }

        if (!$this->isAllowedSubDelete($aDataEntry, $aServiceEntry) || 0 != strcasecmp($_SERVER['REQUEST_METHOD'], 'POST')) {
            echo MsgBox(_t('_Access denied')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }

        if ($this->_oDb->deleteServiceByIdAndOwner($iServiceId, $iEntryId, $this->_iProfileId, $this->isAdmin())) {
            $this->isAllowedDelete($aDataEntry, true); // perform action
            $this->onEventServiceDeleted ($iEntryId, $aDataEntry);            
            $sRedirect = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri];
  
            $sJQueryJS = genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div', $sRedirect);
            echo MsgBox(_t($sMsgSuccess)) . $sJQueryJS;
            exit;
        }

        echo MsgBox(_t('_Error Occured')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
        exit;
    }
 
    function actionServiceAdd ($iServiceId, $sTitle) {
  
        if (!$this->isAllowedAdd()) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }


		if (!($aDataEntry = $this->_oDb->getEntryById($iServiceId))) {
			$this->_oTemplate->displayPageNotFound ();
			return;
		}	

        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);


        $this->_addServiceForm($iServiceId);

        $this->_oTemplate->addJs ('main.js');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('forms_extra.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry['title']));  
    }
 
    function _addServiceForm ($iServiceId) { 
 
        bx_import ('ServiceFormAdd', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'ServiceFormAdd';
        $oForm = new $sClass ($this, $this->_iProfileId, $iServiceId);
        $oForm->initChecker();

        if ($oForm->isSubmittedAndValid ()) {
 
			$sStatus = 'approved';

            $this->_oDb->_sTableMain = 'service_main';
			$this->_oDb->_sTableMediaPrefix = $this->_oDb->_sTableServiceMediaPrefix;
 
            $aValsAdd = array (
                $this->_oDb->_sFieldCreated => time(),
                $this->_oDb->_sFieldUri => $oForm->generateUri(),
                $this->_oDb->_sFieldStatus => $sStatus,
				$this->_oDb->_sFieldAuthorId => $this->_iProfileId 
            );                        
 
            $iEntryId = $oForm->insert ($aValsAdd);
 
            if ($iEntryId) {

                $this->isAllowedAdd(true); // perform action                 
 
				$oForm->processMedia($iEntryId, $this->_iProfileId); 
	  
                $aDataEntry = $this->_oDb->getServiceEntryById($iEntryId);
                $this->onEventSubProfileCreate('service', $iEntryId, $sStatus, $aDataEntry);
   
				$sRedirectUrl = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'service/view/' . $aDataEntry[$this->_oDb->_sFieldUri];
			  
                header ('Location:' . $sRedirectUrl);
                exit;

            } else {

                MsgBox(_t('_Error Occured'));
            }
                         
        } else { 
            echo $oForm->getCode (); 
        }
    }
 
    function onEventServiceDeleted ($iEntryId, $aDataEntry = array()) {

        // delete associated tags and categories 
		$this->reparseSubProfileTags ('service', $iEntryId);
		$this->reparseSubProfileCategories ('service', $iEntryId); 

        // delete votings
        bx_import('ServiceVoting', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'ServiceVoting';
        $oVoting = new $sClass ($this->_oDb->_sServicePrefix, 0, 0);
        $oVoting->deleteVotings ($iEntryId);

        // delete comments 
        bx_import('ServiceCmts', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'ServiceCmts';
        $oCmts = new $sClass ($this->_oDb->_sServicePrefix, $iEntryId);
        $oCmts->onObjectDelete ();

        // delete views
        bx_import ('BxDolViews');
        $oViews = new BxDolViews($this->_oDb->_sServicePrefix, $iEntryId, false);
        $oViews->onObjectDelete();

 
        // arise alert
		//$oAlert = new BxDolAlerts($this->_sPrefix, 'delete', $iEntryId, $this->_iProfileId);
		//$oAlert->alert();
    }        
 
    /*******[END - Service Functions] ******************************/


	//[begin] dealer mapping 
    /**
     * Update profile's location
     * @param $iProfileId user's id which location going to be removed
     * @return true if position was successfully geocoded, and false if doesn't
     */     
    function serviceUpdateSubProfileLocation ($sPrefix, $iProfileId) {
        $iProfileId = (int)$iProfileId;
        $a = $this->_oDb->getSubProfileEntryById($sPrefix, $iProfileId);
        if ($this->_updateSubProfileLocation($sPrefix, 0, $a)) {
            if (!$this->_oDb->isCityLocationExists($a['country'], process_db_input($a['city'], BX_TAGS_NO_ACTION, BX_SLASHES_NO_ACTION)))
                $this->_updateCityLocation(0, $a['city'], $a['country']);
            return true;
        }
        return false;
    }
 
    function _updateSubProfileLocation($sPrefix, $iDelay, &$r) {

        $iDelay = (int)$iDelay;

        $iId = (int)$r['id'];
        $a = false;
  
		$sState = (($r['country']=='US') && $r['state']) ? $r['state'] : '';
 
        if (isset ($r['address1'])) {
            if ($iDelay) sleep ($iDelay);
			 
			if($sState)
				$a = $this->_geocode ($r['address1'] . ' ' . $r['city'] . ' ' . $sState . ' ' . $r['country'], $r['country']);
			else
				$a = $this->_geocode ($r['address1'] . ' ' . $r['city'] . ' ' . $r['country'], $r['country']);
        }

        if (!$a && isset ($r['zip'])) { 
            if ($iDelay) sleep ($iDelay);
            $a = $this->_geocode ($r['zip'] . ' ' . $r['country'], $r['country']); 
        }

        if (!$a) { 
            if ($iDelay) sleep ($iDelay);

			if($sState)
				$a = $this->_geocode ($r['city'] . ' ' . $sState . ' ' . $r['country'], $r['country']);
			else
				$a = $this->_geocode ($r['city'] . ' ' . $r['country'], $r['country']);

        }
  
        if ($a) {
            $this->_oDb->insertSubProfileLocation ($sPrefix, $r['author_id'], $iId, $a[0], $a[1], -1, '', process_db_input($r['city'] . ', ' . $r['country'], BX_TAGS_NO_ACTION, BX_SLASHES_NO_ACTION), process_db_input($r['country'], BX_TAGS_NO_ACTION, BX_SLASHES_NO_ACTION), BX_AUTO_DEFAULT_PRIVACY, 0);
            $bRet = true;
        } else {
            $this->_oDb->insertSubProfileLocation ($sPrefix, $r['author_id'], $iId, 0, 0, -1, '', '', '', BX_AUTO_DEFAULT_PRIVACY, 1);
            $bRet = false;
        }          
        $this->onEventGeolocateProfile ($iId, array ('lat' => (isset($a[0]) ? $a[0] : false), 'lng' => (isset($a[1]) ? $a[1] : false), 'country' => $sCountryCode));
        return $bRet;
    }
	//[end] sub profile mapping


	function actionSubMapMultiple($sType){
  
		switch($sType){
			case 'nightlife': 
				$sTable = $this->_oDb->_sTableNightlife;
				$sSubUrl = 'nightlife';
			break;
			case 'shop': 
				$sTable = $this->_oDb->_sTableShop;
				$sSubUrl = 'shop';
			break;
			case 'school': 
				$sTable = $this->_oDb->_sTableSchool;
				$sSubUrl = 'school';
			break;
			case 'service': 
				$sTable = $this->_oDb->_sTableService;
				$sSubUrl = 'service';
			break;
			case 'hotel': 
				$sTable = $this->_oDb->_sTableHotel;
				$sSubUrl = 'hotel';
			break;
			case 'event': 
				$sTable = $this->_oDb->_sTableEvent;
				$sSubUrl = 'event';
			break;
			case 'transport': 
				$sTable = $this->_oDb->_sTableTransport;
				$sSubUrl = 'transport';
			break;
			case 'food': 
				$sTable = $this->_oDb->_sTableFood;
				$sSubUrl = 'food';
			break;
		}
 

		// Get parameters from URL
		$iCenterLat = $_GET["lat"];
		$iCenterLng = $_GET["lng"];
		$iRadius = $_GET["radius"];

		// Start XML file, create parent node
		$dom = new DOMDocument("1.0");
		$node = $dom->createElement("markers");
		$parnode = $dom->appendChild($node);

		$iCount = (int)getParam('modzzz_location_map_count');
		$sMeasurementType = getParam('modzzz_location_measurement_type');

		switch($sMeasurementType){
			case 'miles':
				$iCalcValue = 3959;
			break;
			case 'kilometers':
				$iCalcValue = 6371;
			break;
			default:
				$iCalcValue = 6371;
			break;
		}

		// Search the rows in the markers table
		$query = sprintf("SELECT `p`.`title`, `p`.`uri`, `p`.`address1`,  `p`.`city`, `p`.`country`, `p`.`thumb`, `m`.`lat`, `m`.`lng`, ( %s * acos( cos( radians('%s') ) * cos( radians( `m`.`lat` ) ) * cos( radians( `m`.`lng` ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( `m`.`lat` ) ) ) ) AS distance FROM `" . $this->_oDb->_sPrefix . "sub_profiles` AS `m` INNER JOIN `" . $this->_oDb->_sPrefix . $sTable . "` AS `p` ON (`p`.`id` = `m`.`id`) WHERE `m`.`subtype` = '{$sSubUrl}' AND `m`.`failed` = 0 AND `p`.`status` = 'approved' HAVING distance < '%s' ORDER BY distance LIMIT 0 , %s",
		  $iCalcValue,
		  mysql_real_escape_string($iCenterLat),
		  mysql_real_escape_string($iCenterLng),
		  mysql_real_escape_string($iCenterLat),
		  mysql_real_escape_string($iRadius),
		  $iCount);
		$result = db_res($query); 
 
		header("Content-type: text/xml");

		// Iterate through the rows, adding XML nodes for each
		while ($row = @mysql_fetch_assoc($result)){
		  $node = $dom->createElement("marker");
		  $newnode = $parnode->appendChild($node);
		  
		  $sCountry = _t($GLOBALS['aPreValues']['Country'][$row['country']]['LKey']);
		  $sCity = $row['city'];

		  if($row['address1'])
			  $sAddress = $row['address1'] . '<br>'. $sCity .', '. $sCountry;
		  else 
			  $sAddress = $sCity .', '. $sCountry;
		 
		  $newnode->setAttribute("url", 'm/location/'.$sSubUrl.'/view/'.$row['uri']);
		  $newnode->setAttribute("name", $row['title']);
		  $newnode->setAttribute("address", $sAddress);
		  $newnode->setAttribute("lat", $row['lat']);
		  $newnode->setAttribute("lng", $row['lng']);
		  $newnode->setAttribute("distance", $row['distance']); 
		 }

		echo $dom->saveXML();
	}


	function actionSubMapSingle($sType, $iItemId){
  
		switch($sType){
			case 'nightlife': 
				$sTable = $this->_oDb->_sTableNightlife;
				$sSubUrl = 'nightlife';
			break;
			case 'shop': 
				$sTable = $this->_oDb->_sTableShop;
				$sSubUrl = 'shop';
			break;
			case 'school': 
				$sTable = $this->_oDb->_sTableSchool;
				$sSubUrl = 'school';
			break;
			case 'service': 
				$sTable = $this->_oDb->_sTableService;
				$sSubUrl = 'service';
			break;
			case 'hotel': 
				$sTable = $this->_oDb->_sTableHotel;
				$sSubUrl = 'hotel';
			break;
			case 'event': 
				$sTable = $this->_oDb->_sTableEvent;
				$sSubUrl = 'event';
			break;
			case 'transport': 
				$sTable = $this->_oDb->_sTableTransport;
				$sSubUrl = 'transport';
			break;
			case 'food': 
				$sTable = $this->_oDb->_sTableFood;
				$sSubUrl = 'food';
			break;
		}
  
 
		// Start XML file, create parent node
		$dom = new DOMDocument("1.0");
		$node = $dom->createElement("markers");
		$parnode = $dom->appendChild($node);
 
		// Search the rows in the markers table
		  
		$query = sprintf("SELECT `p`.`title`, `p`.`uri`,  `p`.`address1`,  `p`.`city`, `p`.`country`, `p`.`thumb`, `m`.`lat`, `m`.`lng`, `p`.`city` FROM `" . $this->_oDb->_sPrefix . "sub_profiles` AS `m` INNER JOIN `" . $this->_oDb->_sPrefix . $sTable . "` AS `p` ON (`p`.`id` = `m`.`id`) WHERE `m`.`subtype` = '{$sSubUrl}' AND `m`.`failed` = 0 AND `p`.`status` = 'approved' AND `m`.`id` = '%s'", 
		  mysql_real_escape_string($iItemId));
 
		$result = db_res($query);

		 
		header("Content-type: text/xml");

		// Iterate through the rows, adding XML nodes for each
		while ($row = @mysql_fetch_assoc($result)){
		  $node = $dom->createElement("marker");
		  $newnode = $parnode->appendChild($node);

		  $sCountry = _t($GLOBALS['aPreValues']['Country'][$row['country']]['LKey']);
		  $sCity = $row['city'];

		  if($row['address1'])
			  $sAddress = $row['address1'] . '<br>'. $sCity .', '. $sCountry;
		  else 
			  $sAddress = $sCity .', '. $sCountry;

		  $newnode->setAttribute("url", 'm/location/'.$sSubUrl.'/view/'.$row['uri']);
		  $newnode->setAttribute("name", $row['title']);
		  $newnode->setAttribute("address", $sAddress);
		  $newnode->setAttribute("lat", $row['lat']);
		  $newnode->setAttribute("lng", $row['lng']);
		 
		}

		echo $dom->saveXML(); 

	}
 
	function actionMapMultiple($sType='location', $iCenterLat=0, $iCenterLng=0, $iRadius=0){
   
		// Get parameters from URL
		//$iCenterLat = $_GET["lat"];
		//$iCenterLng = $_GET["lng"];
		//$iRadius = $_GET["radius"];

		// Start XML file, create parent node
		$dom = new DOMDocument("1.0");
		$node = $dom->createElement("markers");
		$parnode = $dom->appendChild($node);

		$iCount = (int)getParam('modzzz_location_map_count');
		$sMeasurementType = getParam('modzzz_location_measurement_type');

		switch($sMeasurementType){
			case 'miles':
				$iCalcValue = 3959;
			break;
			case 'kilometers':
				$iCalcValue = 6371;
			break;
			default:
				$iCalcValue = 6371;
			break;
		}
 
 		$sSubProfileUri = '';
		switch($sType){
			case 'location': 
 				$sTable = $this->_oDb->_sTableMain;
				$sMapTable = $this->_oDb->_sTableProfile;
			break;
			case 'nightlife': 
				$sSubProfileUri = 'nightlife/';
				$sTable = $this->_oDb->_sTableNightlife;
				$sMapTable = $this->_oDb->_sTableSubProfile;
				$sExtraWhere = "`m`.`subtype` = '$sType' AND "; 
			break;
			case 'shop': 
				$sSubProfileUri = 'shop/';
				$sTable = $this->_oDb->_sTableShop;
				$sMapTable = $this->_oDb->_sTableSubProfile;
				$sExtraWhere = "`m`.`subtype` = '$sType' AND "; 
			break;
			case 'school': 
				$sSubProfileUri = 'school/';
				$sTable = $this->_oDb->_sTableSchool;
				$sMapTable = $this->_oDb->_sTableSubProfile;
				$sExtraWhere = "`m`.`subtype` = '$sType' AND "; 
			break;
			case 'service': 
				$sSubProfileUri = 'service/';
				$sTable = $this->_oDb->_sTableService;
				$sMapTable = $this->_oDb->_sTableSubProfile;
				$sExtraWhere = "`m`.`subtype` = '$sType' AND "; 
			break;
			case 'hotel': 
				$sSubProfileUri = 'hotel/';
				$sTable = $this->_oDb->_sTableHotel;
				$sMapTable = $this->_oDb->_sTableSubProfile;
				$sExtraWhere = "`m`.`subtype` = '$sType' AND "; 
			break;
			case 'event': 
				$sSubProfileUri = 'event/';
				$sTable = $this->_oDb->_sTableEvent;
				$sMapTable = $this->_oDb->_sTableSubProfile;
				$sExtraWhere = "`m`.`subtype` = '$sType' AND "; 
			break;
			case 'transport': 
				$sSubProfileUri = 'transport/';
				$sTable = $this->_oDb->_sTableTransport;
				$sMapTable = $this->_oDb->_sTableSubProfile;
				$sExtraWhere = "`m`.`subtype` = '$sType' AND "; 
			break;
			case 'food': 
				$sSubProfileUri = 'food/';
				$sTable = $this->_oDb->_sTableFood;
				$sMapTable = $this->_oDb->_sTableSubProfile;
				$sExtraWhere = "`m`.`subtype` = '$sType' AND "; 
			break;
			default:
 				$sTable = $this->_oDb->_sTableMain;
				$sMapTable = $this->_oDb->_sTableProfile;
		}

		// Search the rows in the markers table
		$query = sprintf("SELECT `p`.`title`, `p`.`uri`, `p`.`address1`,  `p`.`city`, `p`.`country`, `p`.`thumb`, `m`.`lat`, `m`.`lng`, ( %s * acos( cos( radians('%s') ) * cos( radians( `m`.`lat` ) ) * cos( radians( `m`.`lng` ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( `m`.`lat` ) ) ) ) AS distance FROM `" . $this->_oDb->_sPrefix . $sMapTable . "` AS `m` INNER JOIN `" . $this->_oDb->_sPrefix . $sTable . "` AS `p` ON (`p`.`id` = `m`.`id`) WHERE {$sExtraWhere} `m`.`failed` = 0 AND `p`.`status` = 'approved' HAVING distance < '%s' ORDER BY distance LIMIT 0 , %s",
		  $iCalcValue,
		  mysql_real_escape_string($iCenterLat),
		  mysql_real_escape_string($iCenterLng),
		  mysql_real_escape_string($iCenterLat),
		  mysql_real_escape_string($iRadius),
		  $iCount);
 
		$result = db_res($query); 
 
		header("Content-type: text/xml");

		// Iterate through the rows, adding XML nodes for each
		while ($row = @mysql_fetch_assoc($result)){
		  $node = $dom->createElement("marker");
		  $newnode = $parnode->appendChild($node);
		  
		  $sCountry = _t($GLOBALS['aPreValues']['Country'][$row['country']]['LKey']);
		  $sCity = $row['city'];

		  if($row['address1'])
			  $sAddress = $row['address1'] . '<br>'. $sCity .', '. $sCountry;
		  else 
			  $sAddress = $sCity .', '. $sCountry;
		 
		  $newnode->setAttribute("url", 'm/location/'.$sSubProfileUri.'view/'.$row['uri']);
		  $newnode->setAttribute("name", $row['title']);
		  $newnode->setAttribute("address", $sAddress);
		  $newnode->setAttribute("lat", $row['lat']);
		  $newnode->setAttribute("lng", $row['lng']);
		  $newnode->setAttribute("distance", $row['distance']); 
		 }

		echo $dom->saveXML();
	}


	function actionMapSingle($iItemId){
   
 
		// Start XML file, create parent node
		$dom = new DOMDocument("1.0");
		$node = $dom->createElement("markers");
		$parnode = $dom->appendChild($node);
 
		// Search the rows in the markers table
		  
		$query = sprintf("SELECT `p`.`title`, `p`.`uri`,  `p`.`address1`,  `p`.`city`, `p`.`country`, `p`.`thumb`, `m`.`lat`, `m`.`lng`, `p`.`city` FROM `" . $this->_oDb->_sPrefix . "profiles` AS `m` INNER JOIN `" . $this->_oDb->_sPrefix . "main` AS `p` ON (`p`.`id` = `m`.`id`) WHERE  `m`.`failed` = 0 AND `p`.`status` = 'approved' AND `m`.`id` = '%s'", 
		  mysql_real_escape_string($iItemId));
 
		$result = db_res($query);

		 
		header("Content-type: text/xml");

		// Iterate through the rows, adding XML nodes for each
		while ($row = @mysql_fetch_assoc($result)){
		  $node = $dom->createElement("marker");
		  $newnode = $parnode->appendChild($node);

		  $sCountry = _t($GLOBALS['aPreValues']['Country'][$row['country']]['LKey']);
		  $sCity = $row['city'];

		  if($row['address1'])
			  $sAddress = $row['address1'] . '<br>'. $sCity .', '. $sCountry;
		  else 
			  $sAddress = $sCity .', '. $sCountry;

		  $newnode->setAttribute("url", 'm/location/view/'.$row['uri']);
		  $newnode->setAttribute("name", $row['title']);
		  $newnode->setAttribute("address", $sAddress);
		  $newnode->setAttribute("lat", $row['lat']);
		  $newnode->setAttribute("lng", $row['lng']);
		 
		}

		echo $dom->saveXML(); 

	}


    function isAllowedViewSubLocation ($sType='', $iEntryID, &$aLocation) {
		 return true; 
    }

}

?>